Вы находитесь на странице: 1из 50

Chapter 1 Introducing ASP.

NET - 32

Q: What do I need to get my scripts up and running?


A:You will need a Windows 2000 server or Windows XP development machine, IIS configured,
and the .NET Framework SDK downloaded and installed from www.asp.net.

Q:Will I have to recode my old ASP Scripts?


A: Classic ASP pages will happily run alongside ASP.NET scripts.

Q: Can I rename my ASP files to ASPX files?


A: If you want to upgrade your scripts to run under .NET, you will first need to make some
syntactical changes to your code.

Q: Will my existing investment in third-party components be wasted?


A: Not necessarily,ASP.NET pages can use COM components to give you a transition period, but
many of the functions you previously looked to bought-in components to perform, you can now
achieve within the .NET framework for free.

Q: Will I be able to deploy on non-Windows platforms?


A: Currently ASP.NET requires IIS. Having said that, several Open Source projects are under
way to port .NET to non-windows platforms, but as yet, none are complete enough to be certain
what functionality will be brought across and how successful they are. One intriguing project aims
to deliver .NET functionality by running the CLR within the Java Virtual Machine, meaning that
you will be able to deploy .NET on any platform where a Java Virtual Machine is available.Most of
these development efforts are concentrating on
core .NET services, such as a C# compiler and so on, though at the time of this writing, none
have announced support for ASP yet.
www.syngress.com

Q: Are there any ASP.NET hosting companies?


A: More companies are coming out to support ASP.NET all the time.Two are Orcsweb
(www.orcsweb.com), who host several ASP community Web sites such as www.aspalliance.com,
and Brinkster (www.brinkster.com), who even provide free hosting!

Chapter 2 ASP.NET Namespaces


Q: Where are the namespaces located? How do I find them?
A: All of the .NET namespaces are located in assemblies (previously known as dynamically linked
libraries, or DLLs). For example, System is located in the file System.dll. Note, however, that
namespace names do not always represent the DLL files they are located in. For example,
System.Web.UI is located in System.Web.dll, not in System.Web.UI.dll.
Q: What namespaces are automatically imported into ASP.NET pages?
A: System, System.Collections, System.IO, System.Web, System.Web.UI,
System.Web.UI.HtmlControls, and System.Web.UI.WebControls all are imported
implicitly by ASP.NET; you do not need to make explicit references to these.
Q: Do I have to import namespaces not included in the previous list?
A: No, there is no requirement to import additional namespaces. If you like, you can just reference
an object not imported by default by its full namespace name. For example, if you don't import the
System.Drawing namespace, you could use the following line in your code:
Dim objColor as System.Drawing.ColorConverter
Had you imported the System.Drawing namespace, you could simply use the following:
Dim objColor as ColorConverter
Q: Does importing namespaces add overhead to my applications?
A: Simply importing namespaces does not add overhead.The objects within the namespace are
loaded only if they are needed, so you could import every namespace in the .NET Framework
and notice no performance hit.
www.syngress.com
Q: Is there a way to view an assembly's methods and objects without programming
or using the System.Reflection objects?
A: Absolutely! The Intermediate Language Disassembler enables you to view the technical details
of any .NET assembly.You can run it from the command prompt with the command
ildasm.exe.You can also use the object browser in Visual Studio .NET, which provides a more
user-friendly listing of the objects and their methods/properties. Both of these methods are
excellent tools for examining namespaces that you are curious about.
Q: How can I deploy custom namespaces?
A: Thanks to the .NET Framework, deploying namespaces and applications is very easy: all that
is required is to copy the files to the target computer.There is no need to install or register
assemblies or applications because the Common Language Runtime handles everything for
you.There is one requirement, however, if you want the CLR to make custom assemblies
automatically available to your applications: Place them in a \bin directory in your application
folder.Assemblies in this folder are automatically loaded by the .NET runtime, though you can
manually load assemblies that are not in this directory. See the .NET Framework Documentation
for more details.
Chapter 3 ASP Server Controls - 171
Q: How much will ASP syntax change during the transition from Beta 2 to the
final version?
A: Microsoft has "predicted" that there will be no syntactical changes.This should be good news
to developers who were faced with some confusion when certain classes were dropped, added,
and modified during the last transition from Beta 1 to Beta 2.
Q: What happens to the existing ASP applications when the .Net Beta 2 SDK is
installed and .aspx files enter the picture?
A: Nothing! The good news is that files extensions used by ASP (.asp, .asa, etc.) are completely
separate from the ones used by ASP.NET (.aspx, .asax, .ascx, etc.) and do not override each
other even in the same directory. The bad news is that settings made in the global.asa file are not
accessible to those made in the global.asax file, and therefore you have to redo some setting to
get some consistency.
Q: Are paths such as HREFs in user controls relative to the user control or to the
host page that they are in?
A: The paths are relative to the user control and not to the host page. This makes it much easier
for the user control to find things irrespective of what directory the calling .aspx file is. Another
interesting feature in paths is that you can use the "~" to represent the application root to shortcut
the use of the Request Application path. This really makes the building of large Web sites more
manageable.
Chapter 4 Configuring ASP.NET - 224
Q: Should I modify the machine.config file or create a web.config file for my
application?
A: That depends on the situation. If you have multiple applications running on a server, and
several configuration options need to be shared between them, then place the shared
configuration settings in the machine.config and any application specific settings in individual
web.config files. If you only have one application on your server, just create a web.config file with
all your configuration settings.
Q:Why should I use configuration files at all? Can't I just define everything in
my application?
A: Some options available within the configuration files are not available within an application.
One good example of this is the use of compilation options. If you aren't working at this level of
configuration, then there are still several advantages to using the configuration files:They provide
a single reference point for configuration, configuration options are cached and load quickly, and
they enable you to distribute changes to static variables within your application easily.
Q: I don't understand what some of the configuration options do. How can I
find out more about them?
A: There are two resources that I highly recommend. The first is Microsoft's MSDN site, which
contains all of the ASP.NET documentation. The second is hands-on practice. If want to learn
everything about a configuration option, try it yourself in as many ways as possible.
Q: Are the configuration files case-sensitive?
A:Yes! Make sure that you follow the case guidelines for working with your configuration files. If
your configuration isn't working correctly, a good thing to look at is the case formatting of your
configuration files.
Chapter 5 An ASP.NET Application - 262
Q: Must I have a Global.asax?
A: A Global.asax is not required; only use one if you need to. You will not need a Global.asax
unless you want to use events or static variables, for example. Application, session, and cache
values do not depend on your writing a Global.asax.
Q: Are there any security risks associated with session and application variables?
A: As the state information is stored in storage (server memory or a database) that the user has
no direct access to, providing databases are secured, there is no direct security risk. Having said
that, ensure that application variables do not contain sensitive information, as they are accessible
to the whole application and to all users within it.
Q: Should I use application, cache, or static variables?
A: Use whichever is appropriate for your situation; if in doubt, use application variables. For
simple values where the names are known beforehand and do not change, you may find static
variables give you cleaner code and faster processing. Cached values are excellent for situations
where users will frequently need to read the same data or where the application occasionally
needs to refresh this data while the application is running. Application variables are probably best
in cases where users might need to both read and
write values to the variables often, and the variable names are not necessarily known
beforehand.
Q: Can I use application state in a Web farm?
A:Yes, but your application data will only be visible to the process in which it is running. If you
want this data to be shared, then you should store it in an external store instead, such as a
database. For this reason, application state should not be used in a Web farm or a load-balanced
environment when critical values are required.
Q: Can I use session state in a Web farm?
A:Yes, but carefully consider all the implications. Storing session state either puts a load on your
servers, or network, or both.
Chapter 6 Optimizing Caching Methods - 297
Q: I have been asked to migrate an application from ASP to ASP.NET. In the ASP application,
several third-party utilities have been used to provide for caching. Should I use these or use
ASP.NET's internal caching?
A: Use ASP.NET's caching when possible.With automatic scavenging features and integrated
memory management,ASP.NET provides a more tightly integrated caching system than existing
third-party utilities.
Q:Within my application, there is a table populated with data from several different databases.
How could I best implement caching in order to share this populated table between multiple
pages of my application?
A: Use fragment caching to cache a user control that builds your table. Items stored in the cache
are accessible throughout the application.
Q: I am concerned about the use of memory on my server. Prior to implementing caching, the
memory utilization of the system was fairly low, but after adding the caching features to every
page of my application, the memory utilization has gone up quite a bit. Is it possible to add so
many items to the cache that I begin to run into a lack of memory resources?
A: This is possible if all of your items are cached using data caching with the parameters set to
never remove the data from cache. However, by caching any data without this parameter opens
the cached data up to be removed from the cache if the system becomes low on resources.
Q: Which is the overall best method of caching?
A: There is no "best" method. Each of the different caching options apply under different
circumstances, and all of them provide an overall application performance increase when used
properly.
Chapter 7 Introduction to ADO.NET:A Simple Address Book
Q: Where is the best place to put the connection string?
A: In this chapter, we put our samples in the web.config file. This provides a central point to
administer the connection strings, and allows for a reasonable level of security. You should guard
the web.config from prying eyes regardless of where the connection string is. You really have a
lot of options for placing the connection string. You can put the connection string in an encrypted
in a file, custom object, and so on. The best place really depends on your environment, the
applications purpose, and the level of security desired.
Q: Can I reuse a connection?
A:Yes, connections can be reused. Remember to test for state before you do, as ADO.NET may
close the connection if it thinks it is not being used. You cannot use a connection twice at the
same time. It would not be wise to open a connection at the application level, as you could very
easily end up with simultaneous attempts to use the same connection.
Q: In SQL Server, which data type is more suitable for a primary key, INT,
BIGINT or a uniqueidentifier?
A: Generally speaking, the INT going to be sufficient. An INT can hold between -2,147,483,648
and 2,147,483,648. That is a lot of records. If you were to seed an identity column with
-2,147,483,648 negative number and insert one record a second, it would take 136 years to use
all of them up. If you need more than that, then BIGINT is an alternative, but uniqueidentifier
would probably be more appropriate. The other good use for the uniqueidentifier is to keep
disconnected records from colliding with one another. This is often an issue with replication, and
the uniqueidentifier is the method used to prevent it.
Q: How can I add a record to Access and return the ID of the new record in the
same call?
A:Yes, you can. Access 2002 with ADO.NET supports the @@IDENTITY function. This function
returns the last identity that was written in your session. This ensures that the identity value that
you got was not from another user's session.
Q: How can I add a record to Microsoft SQL Server and return the ID of the
new record in the same call?
A: The technique for returning the identity in SQL server is much the same as for Access;
however, you have a couple of other options. You can return the identity as a return value. You
can create an output parameter that is populated after the insert. You can also select the
@@IDENTITY and return a record to the caller. The latter is not the most efficient way. The
return value and the output parameter are comparable; however, the return value is limited to a
data type of integer, while the output value can be any data type that SQL Server supports.
Chapter 8 Using XML in the .NET Framework - 414
Q: What is the difference between DOM Core 1 API and Core 2 API?
A: DOM Level 2 became an official World Wide Web Consortium (W3C) recommendation in late
November 2000. Although there is not much of difference in the specifications, one of the major
features was the namespaces in XML being added, which was unavailable in prior version. DOM
Level 1 did not support namespaces. Thus, it was the responsibility of the application
programmer to determine the significance of special prefixed tag names.DOM Level 2 supports
namespaces by providing new namespace-aware versions of Level 1 methods.
Q: What are the major features of System.XML in the Beta 2 edition?
A: The most significant change in the Beta 2 edition was the restructuring the XmlNavigator
Class. XmlNavigator initially was designed as an alternative to the general implementation of
DOM. Since Microsoft felt that there was a mismatch in the XPath data model and DOM-based
data model, XmlNavigator was redesigned to XpathNavigator, employing a read-only mechanism.
It was conceived of using with XPathNodeIterator that acts as an iterator over a node set and can
be created many times per XPathNavigator. Alternatively, one can have the DOM implementation
as XmlNode, and methods such as SelectNodes() and SelectSingleNodes() can be used to
iterate through a node set. A typical code fragment would look like this:
Dim nodeList as XmlNodeList
Dim root as XmlElement = Doc.DocumentElement
nodeList =
root.SelectNodes("descendant::account[child::State='OH']")
Dim entry as XmlNode
For Each entry in nodeList
'Do the requisite operations
Next
www.syngress.com
Although XPathNavigator is implemented as a read-only mechanism to manipulate the XML
documents, it can be noted that certain other classes like XmlTextWriter can be implemented
over XPathNavigator to write to the document.
Q: How is XPath different from XSL Patterns?
A: XSL Patterns are predecessors of XPath 1.0 that have been recognized as a universal
specification. Although similar in syntax, there are some differences between them. XSL pattern
language does not support the notion of axis types. On the other hand, the XPath supports axis
types. Axis types are general syntax used in Xpath, such as descendant, parent, child, and so on.
Assume that we have an XML document with the root node named Bank. Further, assume that
the Bank element contains many Account elements, which in turn contains account number,
name, balance, and state elements. Now, suppose that our objective is to retrieve the Account
data for those customers who are from Ohio. We can accomplish the search by using any one of
the following alternatives:
_ XSL Pattern Alternative: Bank/Account[child::State='OH']
_ XSL Path 1.0 Alternative: descendant::Account[child::State='OH']
Which of the above alternatives would you use? That depends on your personal taste and on the
structure of the XML document. In case of a very highly nested XML document, the XSL Path
offers more compact search string.
Chapter 9 Debugging ASP.NET
Q: Is the Try-Catch-Finally block available in C# as well?
A:Yes, the Try-Catch-Finally block is available in both VB.NET and C#.
Q: Can I use both structured and unstructured error handling within a function/ subroutine?
A: No, you cannot use both error handling mechanisms at the same time. It is recommended you
use structured error handling in .NET.
Q: When I try to run my ASP.NET application in VS.NET, I encounter this error message "Error
while trying to run project: Unable to start debugging on the Web server. The project is not
configured to be debugged."Why does this occur?
A: This is caused by the setting of the debug attribute within the <compilation> element. During
development stage, set the value of the debug attribute to "true." Remember, however, to set this
attribute to "false" when you are ready to deploy your application.
Chapter 10 Web Services
Q:Why replace COM objects with Web Services?
A:Web Services have a platform neutral interface. This enables Web Services to be easily utilized
by multiple clients on different platforms developed with different programming languages. Note
that existing COM components can be wrapped by Web Services.
Q: Can I create access to Web Services from a standard ASP page?
A:Yes, you can; however, you might want to look into Microsoft's SOAP toolkit.
Q: How do I know I need Web Services?
A: If you have data that is needed by various customers (different departments, different levels of
management, vendors, industry partners, consumers and so on) and getting to that data is
hindered or prevented by issues involving platform, programming language, legacy hardware or
other types of incompatibility, developing Web Services can help.
Q: What area of development are Web Services best for?
A: I believe that Web Services development like COM development will remain in the hands of
the middle tier programmer. Traditionally this was accomplished with C++ and VB programmers,
however simple data access type components may be developed by intermediate and advanced
ASP developers. While this might still be the case,ASP.NET developers need a firmer grasp of
programming with a strongly typed compiled language then their ASP predecessors. This makes
the ASP.NET developer more of a middle tier
programmer and less of a front-end Web developer. Since building and deploying Web classes
and Web Services are relatively easy with VS.NET as compared to traditional COM development.
I think the proportion of components built by the ASP developer (using ASP.NET) will be larger
than it has been in the past.
www.syngress.com
Q: Is it possible to try out Web Services using only my local computer?
A:Yes, it is. Using the WSDL.exe command line tool, you can point to any Web server. This is
even easier with the VS.NET UI. Simply right-click Web references, then select any Web service
from the UDDI directory or your local machine, or simply type the URL of a disco file on any
server. You can easily generate a WSDL proxy and use it as long as you are connected to the
Internet.
Q: I'm currently in the process of migrating. What considerations should I take
with my existing COM components?
A: Here are a few things to consider:
_ Who is the customer? If the customer is only within the intranet and there are no external
customers in the foreseeable future, an existing DCOM infrastructure needn't be changed.
_ What type of clients do I have? If the client is a desktop application, switching to Web Services
would require updating the client, which may include updating the OS, and possibly the hardware
so that the client has enough memory to host the .NET Framework.
_ Will I need to support Mobile devices in the near future? Using the .NET Mobile Framework to
access Web Services is as simple as it is with .NET. Updating the existing clients to .NET will
make adding future clients simple and cost-effective.
Chapter 11 Creating an XML.NET Guestbook
Q:Why does the add.aspx code need the inline XML schema?
A: Add.aspx uses the schema to retrieve the way it needs to write the data to the XML file in the
proper order. Say that instead of name before e-mail, you had e-mail before name; add.aspx
would write the row with the e-mail field first instead of the name field.
Q:Why won't the simple guestbook show?
A: .NET expects www.w3.org/1999/XSL/Transform as the XSLT namespace. This does limit you
a bit, since the Working Draft version is extremely better than the 1999 version.
Q: I get an error that says, "compilation error, (addClick or Page_Load) is not part
of asp:(add.aspx or viewbook.aspx)".What does that mean?
A: Unfortunately, some of the error handling for ASP.NET still needs tweaking; this is a perfect
example. When running the aspx page, it will spit out errors when it finds them within the asp
objects, but is not very good at reporting errors within the subs located within the <head> tag.
When you see these errors, check the code and try again.
Chapter 12 Creating an ADO.NET Shopping Cart
Q: My project has a few different pages in it. Unfortunately, the last page I created is the one that
is loaded when I run the project. How do I set the first page to open when I run the project?
A: In your Project Explorer, right-click the file you want and set it to Start Page.
Q: I am working with the XmlDocument object in my code-behind page, and I am not getting any
IntelliSense.What am I doing wrong?
A: Make sure you have included "Using System.Xml" in the top section of the page.
Q: I just started using VS.NET Beta 2 and I am trying to create a WSDL proxy to my Web
Service. Is there an easy way to do this in VS.NET?
A: Right-click your Project Explorer and select Add Web reference.
Q: I renamed a file in my Solutions Explorer, but the corresponding ".aspx.cs" and ".aspx.resx"
names did not change. Because of this, the project will not compile correctly. How can I fix this?
A: In your Solutions Explorer, make sure all child files are collapsed in the parent when renaming
and this will change all the associated files. If you have already changed one file, change it back
to the name prefix of the other files, then collapse the children and rename it to the new
name.Also, check the first line in the .aspx page and ensure that the Inherits attribute lists the
correct filename.
Chapter 13 Creating a Message Board with ADO and XML
Q: When designing applications, do I need to design them in an Object- Oriented manner?
A: Absolutely not, although when applications are designed in an OO manner, they are typically
more scalable and maintainable, and allow for the use of multiple User Interfaces.You are not
forced to create applications in an OO manner, but good programming practices typically stress
Object Orientation.
Q: Are there any performance issues when using an OO approach versus a more procedural
approach?
A:Yes, typically the OO approach adds a bit of overhead to everything you do. For instance, the
creation of the custom DataSet in order to view Boards, Threads, and Posts spends extra time
that wouldn't have been lost if you had gone directly to the database instead of accessing the
data through objects. The price of scalability and maintainability is a possible performance loss.
Luckily, with .NET, execution is very fast after the initial compile, so it's also very likely that you
would never notice the speed loss.
Q: How important is it to use Validation controls?
A:Very important. In ASP 3.0 and 2.0 (heck, even ASP 1.0), all validation had to be done by
hand. Empty fields needed to be validated as well as e-mail addresses and URIs.With Validation
controls,ASP.NET does all of this for us, allowing us to focus more on the logic and business
rules in our application.
www.syngress.com
Q: How can I ban a list of IP addresses in the future?
A: First, you would need to create a table in your database to store the list of IP addresses, and
provide a way for an administrator to enter an IP address into it.Then, at every page you want to
disallow this list of IP addresses from viewing, compare the IP address of the requesting user and
compare it to the list of IP addresses you have banned. If it exists in your list of banned
addresses, redirect them to another page or do whatever else you feel is appropriate.

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.

The XML Web Control


The ASP.NET XML Web control is a Web control designed to display XML data in an ASP.NET
Web page. To use the XML Web control in an ASP.NET Web page, simply use the following
syntax:
<asp:xml runat="server" id="ID" />
In order to display XML data, you must specify where the Web control should get the XML data
from. You can set one of the three following properties to specify where the Web control should
retrieve the XML data:

* 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.

The DocumentSource and DocumentContent properties are string properties. DocumentSource


specifies a physical file specifying where the XML data resides. If you do not have the XML
content in a file, but within a string variable, you can simply assign the string containing the XML
content to the DocumentContent property.

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

set objCDO = nothing


%>
Question: How can I retrieve emails from a service like Yahoo! Mail?
Answer: Many Web-based email providers (as well as ISPs), allow individuals to view their email
through the POP3 protocol. This protocol specifies how emails should be retrieved from an email
inbox.
By default, ASP provides no mechanism for retrieving emails via the POP3 protocol. Therefore, to
access a POP3 email account via an ASP page you will either need to build or buy a POP3
component.
Question: How can I validate an email address using VBscript?
Answer: Thanks to Anders Rask for porting the validation code to VBscript! Using regular
expressions, you can validate an email address using the following code:
<html>
<head>
<title>VBscript email validation</title>
</head>
<body>

<%
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

' Create regular expression:


regEx.Pattern ="^[\w-\.]{1,}\@([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$"

' Set pattern:


regEx.IgnoreCase = true

' Set case sensitivity.


retVal = regEx.Test(sEmail)

' Execute the search test.


If not retVal Then
exit function
End If

RegExpTest = true
End Function
Else
%>

<form action="emailCheck.asp" method="post">


<input type="text" name="emailAddress">
<input type="submit" value="submit">
</form>

<%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

Response.write("Mail was Sent")

'You must always do this with CDONTS.


set objMail = nothing
%>
Question: How can I validate an email adress using Jscript?
Answer: Thanks to the help of Hack Kampbjorn my email validation routine using Javascript's
regular expressions:
<html>
<head>
<title>regex_new.asp</title>
</head>
<body>

<script language="javascript" runat="server">


function test(src) {
var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
return regex.test(src);
}
</script>

<%
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.

The AttachFile method can be used like:


CDONTS_Object.AttachFile(Physical_Path_to_File, English_Name_For_File)
Below is a sample script (written by Rob Taylor) that sends an email attachment:
<%
Option Explicit

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

Response.write("Mail was Sent")

'You should always do this with CDONTS.


set objMail = nothing
%>

Question: How can I display line breaks in an email message?


Answer: When starting out with sending email messages through ASP pages, many developers
have trouble inserting line breaks. To accomplish this, simply insert a vbCrLf wherever you want a
line break in your email's body. For example, using CDONTS, we'd have:
Dim objMail
Set objMail = Server.CreateObject("CDONTS.NewMail")

'Set the various CDONTS properties...


objMail.To = "whatever@wherever.com"
' ...
objMail.Body = "This is on line 1" & vbCrLf & _
"And this is on line 2!"
Question: How can I have my ASP page send HTML-formatted email?
Answer: Using CDONTS, you can send email messages in HTML format. CDONTS contains two
properties named BodyFormat and MailFormat. These properties should be set to the value of
zero (0), and the email will be sent in HTML format! With HTML formatted email, you can embed
hyperlinks and even images into your email messages!
Question: How can I share cookies between my server-side scripts (ASP) and my client-side
scripts (e.g., JavaScript in the browswer)?
Answer: User ChaCha worked on this for a while and discovered the answer! I simply pass along
the information:

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

For Each Cookie in Request.Cookies %>


<tr>
<td colspan="2">
<font face="ariel, helvetica" size="3">
The Name of the Cookie is: <font color=#FF0000>
<%=Cookie%></font><br>
</font>
</td>
</tr><%

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:

-- In Page1.asp create a cookie and redirect the user to Page2.asp


-- In Page2.asp, check to see if the cookie exists. If it does, then the user supports cookies, else
he doesn't!
Question: When using the FSO, my ASP page tends to "hang", but doesn't report any errors.
Answer: This question has been arising more commonly since around October 2001. 9 times out
of 10, it's due to the virus scanner in place.

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")

Set objTS = objFSO.OpenTextFile(filename)

'Now, read the contents of the file into a string


Dim s
s = objTS.ReadAll

'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

'How many random elements from the array do we want?


Const n = 10

For i = 1 to n
value = aFiles(Int(Rnd * UBound(aFiles)))

'Now do something with value


Next
Question: How can I read the contents of a file, line-by-line, into an array?
Answer: Other scripting languages allow for a developer to read the contents of a text file, line-by-
line, into an array. Unfortunately, this is not an inherent feature in VBScript or JScript. However,
you can easily add such functionality by creating your own function!

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")

Set objTS = objFSO.OpenTextFile(filename)

'Now, read the contents of the file into a string


Dim s
s = objTS.ReadAll

'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:

-- strWildcards - a comma-delimited list of wildcards to delete.


-- strDirectory - the directory to delete the files from (must end with a backslash).
Sub DeleteFileExtensions(strWildcards, strDirectory)
'Turn off error handling
On Error Resume Next

'Create an instance of the FileSystemObject


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

'Loop through each wildcard extension to delete


Dim aExtensions
aExtensions = split(strWildcards, ",")
Dim i
For i = LBound(aExtensions) to UBound(aExtensions)
'Delete the file
objFSO.DeleteFile(strDirectory & aExtensions(i))
Next
End Sub
That's all you have to do! To utilize this function you could use the following code:
Dim strWildcardsToDelete, strDirectory
strDirectory = "C:\SomeDirectory"
strWildcardsToDelete = "*.txt,*.inc"

DeleteFileExtensions strWildcardsToDelete, strDirectory


Question: How can I rename a directory on my Web server?
Answer: In a previous FAQ - How can I rename a file on my Web site through an ASP page?
<http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=36> - we looked at how to rename a
file on a Web server's filesystem. To accomplish this, though, you had to resort to clever
programming, since the FileSystemObject does include any sort of Rename method. In order to
rename a file, you need to use the MoveFile method like so:
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

objFSO.MoveFile Server.MapPath("/someDir/Foo.asp"), _
Server.MapPath("/someDir/Bar.asp")

Set objFSO = Nothing


which will rename the file on your Web site /someDir/Foo.asp to /someDir/Bar.asp.

For more information on Server.MapPath be sure to read: Using Server.MapPath


<http://www.4guysfromrolla.com/webtech/121799-1.shtml>

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")

objFSO.MoveFolder "C:\Foo", "C:\Bar"

Question: What, exactly, is the FileSystemObject?


Answer: The FileSystemObject, or FSO, is an often used component to access the web server's
file system. For example, you can create files, read the contents of files, determine whether or not
a folder or file exists, iterate through the contents of a folder or directory, or any other number of
file system-related tasks. You can create an instance of the FileSystemObject component in an
ASP page with the following code:
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Once you create an instance of this component, you can access its many properties and
methods. For example, say that you wanted to output the contents of the text file C:\SomeFile.txt.
The following code could be used:
Const fsoForReading = 1

Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Open the text file
Dim objTextStream
Set objTextStream = objFSO.OpenTextFile("C:\SomeFile.txt", fsoForReading)

'Display the contents of the text file


Response.Write objTextStream.ReadAll

'Close the file and clean up


objTextStream.Close
Set objTextStream = Nothing
Set objFSO = Nothing
Understand that the FileSystemObject's purpose is to allow an ASP page (or VB program, or
WSH file) to have access to the machine's file system. Since your ASP pages reside and are
executed on the web server, when using FSO to access the file system, you are accessing the
web server's file system. You cannot access the client's file system using the FileSystemObject in
your ASP code.

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.

Fortunately the FileSystemObject contains a couple of methods to help us create


temporary/random/unique file names. The first method, GetTempName, returns a temporary file
name. For example, the code:
<%
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
Response.Write objFSO.GetTempName

Set objFSO = Nothing 'Clean up!


%>
Might output: rad295F4.tmp
or: rad4ED11.tmp
or: radC6F92.tmp

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:

0 - Returns the Windows folder (like C:\WINNT\)


1 - Returns the system folder (most likely C:\WINNT\system32)
2 - Returns the temporary folder (like C:\WINNT\Temp)

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")

Dim strTempFolder, strTempFileName


strTempfolder = objFSO.GetSpecialFolder(fsoTempFolder)

strTempFileName = strTempFolder & "\" & objFSO.GetTempName()

Response.Write "The temporary folder is: " & strTempFolder


Response.Write "<br>A temp. file name: " & strTempFileName

Set objFSO = Nothing 'Clean up!


%>

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")

'This will return the path to the temporary folder


Response.Write objFSO.GetSpecialFolder(2).Path

Set objFSO = Nothing


%>
Question: How can I read the contents of a text file through an ASP page?
Answer: To read the contents of a text file, use the FileSystemObject.
In an earlier FAQ <http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=23> we discussed
that the general purpose of the FileSystemObject (FSO) is to allow access to the host computer's
file system. One common function when dealing with a computer's file system, is reading the
contents of a file. FSO provides a TextStream object that is useful for reading and writing the
contents of a text file. In this FAQ, we will discuss how to use
the TextStream object to read the contents of a file.

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

const strFileName = "D:\scott\resume.txt"


const fsoForReading = 1

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

Question: How can I copy a file using ASP?


Answer: You can copy a file in ASP using the Scripting.FileSystemObject which is built into the
Windows scripting engine. I have written the following CopyFile() function that you can use to
copy a file. Note that the anonymous Internet account user (usually IUSR_machinename), must
have read access to the directories and file that are involved in the copy). For more info on the
IUSR_machinename account be sure to read this FAQ
<http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=23>:
'*****************************************************************
'Name : CopyFile
'Purpose : Copy file from source to destination
'Input: StrFileSource - path to file you want to copy
' StrFileDestination - path that file destination
'Output: StrError - Error Message
'Author : Ian Stallings
'Date : 09/27/00
'*****************************************************************

function CopyFile(strFileSource, strFileDestination, strError)

if strFileSource = "" OR strFileDestination = "" then


strError = "Error - You must supply both a source and a destination"
exit function
end if

set fso = Server.CreateObject("Scripting.FileSystemObject")


if Not fso.FileExists(strFileSource) then
strError = "Error - Source file does not exist"
exit function
end if

if strError = "" then


Set f2 = fso.GetFile(strFileSource)
f2.Copy(strFileDestination)
Set f2 = nothing
end if

Set fso = 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")

Set objFSO = Nothing


Question: How do I find out if a file exists?
Answer: <%
Set FSO = Server.CreateObject("Scripting.FileSystemObject")
If FSO.FileExists( Server.MapPath( "filename.xyz" ) ) Then
... file exists ...
Else
... it does not ...
End If
%>
The argument to the FileExists method must be the FULL PATH to a file somewhere on your
local system (or LAN, if applicable). You can either give the path explicitly, as in
If FSO.FileExists( "x:\nastyComments\crossposts\answer3.txt" ) Then
or you can give a path that is relative to the location of the currently executing ASP page via
something like
If FSO.FileExists( Server.MapPath( "../images/uglyface.jpg" ) ) Then
Question: How can I programmatically list the contents of a directory on the Web server?
Answer: With the FileSystemObject you can (fairly easily) programmatically obtain all of the files
of a given directory on the Web server. To accomplish this task we'll need to complete the
following steps:

1.) Create an instance of the FileSystemObject object


2.) Use the FileSystemObject to return a Folder object (which contains information about a
particular directory).
3.) Use a For Each ... Next loop to iterate through each file in the Folder object.

So, let's examine some code that will handle this...


<%
'Create the FileSystemObject object
Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")

'Obtain an folder object instance for a particular directory


Dim objFolder
Set objFolder = objFSO.GetFolder("C:\FooBar\Blah\")

'Use a For Each ... Next loop to display the files


Dim objFile
For Each objFile in objFolder.Files
'Print out the name
Response.Write objFile.Path & "<BR>"
Next
%>
That's it! The Folder object contains a slew of information about a particular folder (in this case,
we obtained information about the C:\FooBar\Blah\ directory. If you want to get a listing of
subfolders of a folder, you can use the same technique to iterate through the SubFolders
collection of the Folder object.
Question: How can I delete a file from the Web server's file system?
Answer: The FileSystemObject, which provides access to the Web server's file system, contains
a method called DeleteFile. As its name implies, DeleteFile is used to delete a file from the Web
server's file system.

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")

'Delete the file


objFSO.DeleteFile "C:\Foo\readme.txt", False
Question: How can I create a folder (directory) on the Web server?
Answer: The FileSystemObject contains a CreateFolder method that can be used to create a
folder on the Web server's file system. This method takes one parameter, the path of the folder to
create. For example, to create a FooBar folder on the C:\ drive, you could use the following code:
'Create an instance of 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")

'Create the text file


Set objTS = objFSO.CreateTextFile("C:\MyDirectory\foo.txt")
'Write "Hello, World" to the file
objTS.WriteLine("Hello, World!")

'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

' Specify one of these constants for "sortBy"...


CONST FILE_NAME = 0
CONST FILE_EXT = 1
CONST FILE_TYPE = 2
CONST FILE_SIZE = 3
CONST FILE_CREATED = 4
CONST FILE_MODIFIED = 5
CONST FILE_ACCESSED = 6

' get requested sort order, if not first time here...


' (forward by name is default)
req = Request("sortBy")
If Len(req) < 1 Then sortBy = 0 Else sortBy = CInt(req)
req = Request("priorSort")
If Len(req) < 1 Then priorSort = -1 Else priorSort = CInt(req)

'
' 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

' now start the *real* code...


'
path = Server.MapPath( DIRECTORY )

Set fso = CreateObject("Scripting.FileSystemObject")


Set theCurrentFolder = fso.GetFolder( path )
Set curFiles = theCurrentFolder.Files
'
' And now a loop for the files
'
Dim theFiles( )
ReDim theFiles( 500 ) ' arbitrary size!
currentSlot = -1 ' start before first slot

' 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!

' First, determine which "kind" of sort we are doing.


' (VarType=8 means "string")
'
If VarType( theFiles( 0 )( sortBy ) ) = 8 Then
If reverse Then kind = 1 Else kind = 2 ' sorting strings...
Else
If reverse Then kind = 3 Else kind = 4 ' non-strings (numbers, dates)
End If

'
' 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"

'Create an instance of the FileSystemObject


Dim objFSO
Set objFSO = Server.CreateObject("Scripting.FileSystemObject")
'Get a file object
Dim objFile
Set objFile = objFSO.GetFile(strFileName)
'Get the file size
Dim iFileSize
iFileSize = objFile.Size

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: Does ASP.Net still recognize the global.asa file?


Answer: ASP.Net does not recognize the standard ASP global.asa file. Instead it uses a file
named global.asax with the same - plus additional - functionality.

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.

Question: What is the process-flow for ASP.Net?


Answer:1. User requests an ASPx page in their browser
2. An HTTP requests is sent to IIS
3. The xspisapi.dll isapi filter intercepts the request and passes the request on to the XSP worker
process (xspwp.exe)
4. Xspwp takes care of handing the request to the appropriate HTTPModules and finally an
HTTPHandler as defined in the configuration files.
5. The ASPX page is read from the HD or cache and server code is loaded into memory and
executed.
6. The server side code outputs normal HTML which is handed back through the chain of
modules and eventually to IIS, which sends the response back to the client's browser.
7. If the user clicks or otherwise acts on an HTML element (say, a textbox) that has a server side
event handler, the form is posted back to the server with hidden form fields containing information
as to what control and event occurred. Some controls do not automatically post by default, but
wait for a button_click event to post. This is configurable by the developer.
8. The ASPx page is again loaded into memory using the same sequence of events as before,
but this time ASP.net reads in the hidden form field data and automagically triggers the
appropriate _OnChange, OnClick and other appropriate event handlers.
9. Resulting HTML is sent to the browser
10. The process continues in a continual "Post Back" cycle.

Definition of HTTP Modules:


HTTP modules are a logical replacement for ISAPI filters. Modules are a class that can
participate in every web request. This is appropriate for code that should run on every request,
such as caching, authentication or state management

Definition of HTTP Handlers:


HTTP Handlers provide the end point in the processing of a web request and are equivalent to
ISAPI Extensions today. For example, many handlers can be involved in the request for an
ASPX page, but only 1 handler is invoked. The handler runs after the HTTP modules have
run. Which handler is invoked is determined by configuration settings in the config.web
file. Handlers are assigned to handle requests based on the extension of the page requested.

Question: Is it possible to run client-side .NET code within a browser?


Answer: The answer to this is yes -- you can create client controls (in any .NET language -- for
example: VB, C#, JScript, Perl, Python, etc) and then easily download them to run in an IE
browser today.

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: What happened to date() and time()?


Answer: In ASP.Net you should use:
System.DateTime.Now.ToShortDateString() and System.DateTime.Now.ToShortTimeString()

Question: What's the .NET equivalent for classic ASP's objRS.MoveNext?


Answer: SQLDataReader.Read() or ADODataReader.Read()

Question: How should I destroy my objects in ASP.Net?


Answer: ASP.Net actually has very solid internal garbage collection so this should not be an issue
as it was in previous versions of Active Server Pages.

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.

Question: Does ASP.Net Beta 1 support WSDL?


Answer: No, ASP.Net Beta 1 supports SDL but not WSDL. Beta 2 is expected to support WSDL.
Question: I'm getting an error trying to read a file from the FileStream.
Answer: Make sure you are escaping your '\' characters.
Try one of these lines:

objFS = new FileStream("c:\\test.txt", FileMode.Open, FileAccess.Read);


or
objFSt = new FileStream(@"c:\test.txt", FileMode.Open, FileAccess.Read);

Question: How do I subtract days from a date and display it?


Answer: 'Try:

Dim NewTime as DateTime


NewTime = DateTime.Now.Subtract(New TimeSpan(7, 0, 0))
MyTimeControl.Text = NewTime.ToString()

'You can also format the output with something like:


MyTimeControl.Text = NewTime.ToShortDateString()

Question: What's the equivalent to the vbCrLF constant in VB.Net?


Answer: Do:
Imports Microsoft.VisualBasic.Compatibility.VB6.Constants
To get the VB constants like vbCrLf, vbCr, vbLf, vbNullString, etc

COM

Question: Is it true that COM is going away?


Answer: No. In fact Microsoft is making COM more productive and easier to use.

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.

ASP.NET by default uses an MTA based thread-pool (enables us to do async io completions,


etc). For performance reasons, we don't by default attempt to surface the old ASP COM classic
intrinsics via ObjectContext. Instead, components can directly get access to the intrinsics using
the HttpContext.Current static property.
For example:

Dim Request as HttpRequest


Dim Response as HttpResponse

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: Where should the config.web file be located?


Answer: The main config.web file for the site should be in the web root. You can also over-side
the main config file by placing a copy into a sub web and modifying certain settings.

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.

Question: Can the config.web file be used to configure sub-directories?


Answer: You can use config.web files to configure both subdirectories as well as individual
files. To do this you simply need to use the <location path=""> directive within your file to scope
the path of the settings.

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: Why isn't my config.web file recognized any more?


Answer: Config.web has been renamed to web.config for the Beta 2 release.

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:

Dim AppSettings as Hashtable = Context.GetConfig("appsettings")

Dim DSN as String = AppSettings("dsn")


Dim SomeOtherKey as String = AppSettings("someotherkey")

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: How can I pull an AppSetting parameter in the B2 framework?


Answer: Assuming you have a setting in the web.config AppSettings named "MyDSN", the code
below should work.
MyDSN = CStr(ConfigurationSettings.AppSettings("MyDSN"))

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: Where can I download the latest .NET framework SDK?


Answer: You can download it from Microsoft's .N
Question: What platforms will the .Net Framwork run on?
Answer: The Beta 1 version of the .Net Framework will run on Windows 2000, NT Server 4.0,
Windows 98, or Windows ME.

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

Question: What should I install??


Answer: People should always download using the link on www.asp.net. This points to the
asp.net premium download which is what people should use for deployment. It has all of the
runtime features -- and is 18Mb in size.

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:

1) Always install the ASP.NET Premium


2) If you want local docs and samples install the SDK as well
3) If you want VS.NET designer support install it too

Question: Is ASP.Net Beta2 supported on NT?


Answer: No, ASP.Net beta 2 is not supported on NT, but the rest of the framework (Windows
Forms, Client Apps, etc) will work fine.
Question: Where can I order a CD of the .NET Framework SDK?
Answer: You can download it from the DevStore at the URL below.
Question: How can I view the Quick Start application remotely?
Answer: 1. Edit the config.web file under Quickstart root and change the "RemoteHost" value
from "false" to "true". (ie: <add key="RemoteHost" value="true" />).

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: Is it possible to share a cache object across servers in a cluster?


Answer: The Cache object is restricted to being used only within an application running on a
single machine. Microsoft concluded that the performance hit to share the objects cross-process
would be too great to share it across multiple machines in a cluster (because -- unlike session
state -- there are no logical synchronization boundaries to lock across).

Question: Can session variables be accessed from code-behind?


Answer: Yes. You can access the "Session" dictionary within a code-behind file just like you
would if you were accessing it from within an line .aspx file.

For example: Session("Name") = "Scott"

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:

<%@ Page Language="VB" Trace="True" %>

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:

<%@ Page Language="VB" MaintainState="False" %>


or on an individual server control by setting a "maintainstate" attribute:

<asp:datagrid id="MyGrid1" maintainstate="false" runat=server/>

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.

Question: Is it ok to save a dataset in Page ViewState?


Answer: Scott Guthrie from Microsoft recommends that you avoid putting a DataSet into Page
ViewState. The downside with this is that doing so can drastically increase the size of ViewState
that is posted back and forth between round-trips. This can end up making a big performance
difference when connecting to the application
over slow network connections (since you end up having to transmit a lot more data each way).

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.

Question: Do web services support session variables and/or cookies?


Answer: From Scott Swigart @ 3 Leaf Solutions, LLC:
It appears that in Beta 2, a web service client will not store cookies by
default (which means that Web Services that use sessions won't work). If
you want the client to support cookies, then you have to do the following:

using System.Net

wsAdv.Stateful s = new wsAdv.Stateful();


s.CookieContainer = new CookieContainer();
s.DoSomething();
Question: Will I be able to use Output Caching and Web Farm Session State on Windows
Standard edition?
Answer: Yes. Output Caching and Web Farm Session state will be ASP.NET features that work
on Windows Window Server Standard, Windows Advanced Server and Windows DataCenter
Server editions.

VB

Question: What is the comment syntax for VB?


Answer: ' this is a comment or REM this is a comment

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
--%>

Question: Does string manipulation in VB still have bad performance?


Answer: ASP.net has a STRING BUILDER class that doesn't have this flaw.

Dim build As New stringbuilder


HttpWReq = WebRequestFactory.Create("http://www.funinspace.com")
HttpWReq.KeepAlive = False
HttpWResp = HttpWReq.GetResponse()
sr = new StreamReader(HttpWResp.GetResponseStream(), Encoding.ASCII)

Try
line=sr.ReadLine()
lineENC = server.HTMLencode(line) & vbcrlf & "<br>"
build.append (lineENC)

Do While Not IsNothing(line)


line = sr.ReadLine()
lineENC = Server.HTMLencode(line) & vbcrlf & "<br>"
build.append (lineENC)
Loop
Catch ex As Exception
problem.text = ex.Message
End Try

Question: How do I get a new GUID in VB?


Answer:
dim g as new Guid()
g = g.NewGuid()
response.write ("New Guid: " & g.ToString())

OR since the NewGuid() method is static:

Response.Write("New Guid: " & Guid.NewGuid().ToString())

Question: Where are some VB samples for uploading files in ASP.Net?


Answer: There is a VB example at this URL:
http://www.aspwatch.com/c/200038/d99E2DD4290E211D4AEFA00A0C9E95208.asp
Question: How can I generate a random number in ASP.Net?
Answer: 'Here is a simple sample

Dim r As New Random()


Dim i As Integer

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]

If it exists, then delete it.


Then, try launching VS.NET Beta 2 again.

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:
--------------------------------

<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform'>


<xsl:template match="/">
<style>
.value { width:"25%";font-family:courier new; font-size:.8em;white-space=pre;}
</style>
<table border="1" cellspacing="0" cellpadding="3" bordercolor="gainsboro">
<tr>
<th>Division</th>
<th>Revenue</th>
<th>Growth</th>
<th>Bonus</th>
</tr>
<xsl:for-each select='sales/division'>
<tr>
<td class="value"><em><xsl:value-of select='@id'/></em></td>
<td class="value"><xsl:value-of select='revenue'/></td>
<td class="value">
<xsl:if test='growth < 0'>
<xsl:attribute name='style'>
<xsl:text>color:red</xsl:text>
</xsl:attribute>
</xsl:if>
<xsl:value-of select='growth'/>
</td>
<td class="value"><xsl:value-of select='bonus'/></td>
</tr>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
--------------------------------

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.

-------------------------------------

<%@ Page ContentType="text/xml" %>


<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQL" %>
<%@ Import Namespace="System.Xml" %>

<script language="VB" runat=server>

Function GetProductData() As DataSet


Dim connection as New
SQLConnection("server=localhost;uid=sa;pwd=;database=northwind")
Dim command as New SQLDataSetCommand("SELECT * FROM Products WHERE
ProductID<8", connection)

Dim dataset As New DataSet()


command.FillDataSet(dataset, "dataset")

Return dataset
End Function

Sub Page_Load(Sender as Object, E as EventArgs)


Dim DataSet1 as DataSet = GetProductData()
Dim XmlDoc as XmlDocument = New XmlDataDocument(DataSet1)

MyXml1.Document = XmlDoc
End Sub

</script>

<asp:xml id="MyXml1" runat=server/>

-------------------------------------

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: Do I need Visual Studio or another tool to create ASP.Net applications?


Answer: No. Just as the case is with Active Server Pages, you can use almost any tool - including
a standard text editor like Windows Notepad, to create ASP.Net applications.

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.

Question: Do you have to strongly type all variables in ASP.Net?


Answer: Although you can provide type information in .NET, it isn't necessarily required (although
Microsoft does recommend it for performance reasons). For example, you can declare a variable
in VB.NET as:

Dim Name as String

You can also declare it as:


Dim Name

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.

Question: How do I add an existing solution to Source Safe?


Answer: The best way to work with web projects and teams is to use 'File Share' Web access -
set this in Tools Options, and in Project Properties.

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.

Question: How do I set the selected item in a drop-down list?


Answer: Try using

DropDownList.SelectedIndex = DropDownList.Items.IndexOf(New ListItem("ABC"))


or
DropDownList.SelectedItem.Text = "ABC"

Question: When do database connections need to be closed?


Answer: You do not need to explicitly close any database connections when using a DataSet to
obtain data. Instead, the connection will be automatically closed after populating the DataSet
(which makes sense since the DataSet grabs all data in a snapshot operation -- and as such
doesn't need to hold the connection open).

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.

For example (in VB):


Response.Cookies("name").Value = "Scott"
Response.Cookies("name").Path = "/"

The above code will cause the "name" value to apply to everything below the root of the site.

Question: Where can I get information on regular expression validators?


Answer: There is a great deal of useful information at:
http://www.3leafsolutions.com/default/NetRegExpRepository.aspx

Question: What is the difference between "imports" and "using"?


Answer: They provide the same functionality but are language specific. "using" is for C# and
"imports" is for Visual Basic.

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: Response.Write "Hello World" doesn't work. What's wrong?


Answer: In ASP.Net you need to use Response.Write("Hello World"). Parenthesis should be used
when calling both subs and functions.

Question: How does ASP.Net know to process by code server-side?


Answer:
Server-side code in ASP.Net should be located between these tags:
<script language="language" runat="server">
</script>
Question: Where can I find documentation for all the objects and controls in ASP.Net?
Answer: They are on your local system if you have the Framework SDK installed. Search for a file
named 'SDKStart.chm'.

You can also access the documentation online at:


http://msdn.microsoft.com/library/default.asp

Question: When should I use System.Data.SQL versus System.Data.ADO?


Answer: You should always use System.Data.SQL when you are accessing SQL Server. That
assembly was designed specifically for SQL Server so it performs much better.

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: How can I declare radio buttons in ASP.Net?


Answer: Here is an example:
<asp:RadioButton id="reading" GroupName="hobby" runat="server" />reading<br>
<asp:RadioButton id="music" GroupName="hobby" runat="server" />music<br>
<asp:RadioButton id="sports" GroupName="hobby" runat="server" />sports<br>

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:

<%@ Page Language="VB" Explicit="True" Strict="True" %>

Question: How can I access web controls from a code-behind page?


Answer: In the general declaration for your code behind class, create a control variable with the
same name as the id of the control in your .aspx file:

Public Class CodeBehind : Inherits Page


Public ItemsGrid As DataGrid

Protected Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs)


If Not IsPostback Then
ItemsGrid.DataSource = GetMyDataSource()
ItemsGrid.DataBind()
End If
End Sub

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.

Question: How do enable output cache for an ASP.Net page?


Answer: This line at the top of your page:
<%@ OutputCache Duration="60" %>
will cause the page to be cached for 60 seconds.

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.

Question: Is it possible to bind two columns to a hyperlink field in a DataGrid?


Answer: HyperLink columns support only one bound field. You can achieve this with a
TemplateColumn however. Just put an asp:Hyperlink in a template column and construct a
binding expression for the NavigateUrl like this:

<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:

Sub DropDownList1_PreRender(sender as Object, e as EventArgs)


DropDownList1.Items.Insert(0, "")
End Sub

Question: Is it possible to protect my source code so clients can't see it?


Answer: ASP.NET supports a mode of development called "code-behind". This enables you to
partition your code into a separate file from an .ASPX page file (which contains your static html
and server control declarations).

This provides two benefits:


1) Better code/content separation/organization (enabling more tool support, multi-developer
support, localization support, etc).
2) Enabling you to optionally "pre-compile" the code-behind file before deployment on a
server. This step provides (among other things) the ability to protect your source code from direct
access by your customers.
Question: Is it possible to nest DataBound .Net controls?
Answer: Here's how you set up the DataSource property of the nested DataGrid:
<template name="SelectedItemTemplate">
<asp:DataGrid id="DataGrid1" runat="server"
DataSource='<%# DataBinder.Eval(Container.DataItem, "Topics") %>'/>
</template>

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.

Question: How do I set the width of columns in a DataGrid?


Answer: You can use asp:BoundColumns and specify the ItemStyle-Width property.

Question: Is there a sample for how to use Passport authentication in ASP.Net?


Answer: There is a sample located at:
http://www.gotdotnet.com/passportexample/exampleclothing2/webpages/default.htm

Question: How can I dynamically add user controls to a page?


Answer: User Controls can be dynamically loaded. One of the great advantages over include
files here is that the code still compiles and runs as if the user control were in the page to begin
with.

<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>

Question: How can I tell which item is selected in a list control?


Answer:
myList.SelectedItem.Text 'what is displayed
myList.SelectedItem.Value 'the value associated with the item
Question: How can I tell if a DataSet has any data in it?
Answer: Use:
DataSet.Tables.Count
If it is greater than 0 there is at least one DataTable in the DataSet.

Question: How can tell if a DataTable has any data in it?


Answer: Use:
myDataSet.Tables[0].Rows.Count

If the result is larger than zero, there is data in the DataSet.

Question: Is checking the Count property of a DataSet expensive?


Answer: Count is a property (not a method) of the object and exists whether you check it or
not. Overhead here is a bit different than using Count with an ADO RecordSet and classic ASP.

Question: How do I resolve a 'Could not load assembly ...' error?


Answer:
1. Stop the IIS services
2. Open a command prompt and delete all of the files in the c:\winnt\assembly directory
3. Restart the IIS services

You may also want to change the cache size through the registry as listed in this article:

http://www.gotdotnet.com/journal/1129.aspx

Question: How can I reference a specific field in a DataSet?


Answer: You can use:

ds.Tables["Files"].Rows[0]["FileType"].ToString()

The "System.Data.DataRow" class has no property "Columns" but ds.Tables["Files"].Rows[0]


returns a DataRow class that has a indexer for the columns in the row.

Question: I'm getting the error "Type is not defined: 'ADOConnection'"


Answer: "ADOConnection" has been changed to "OleDbConnection" for the beta 2 release of
the .Net Framework.

Question: How can I create a "hidden" ASP.Net form control?


Answer: Most of the controls have a "visible" property, so you should be able to use:
<asp:TextBox ID="abc" Visible="False" Runat="server"></asp:TextBox>

Table 1-5 Visual Basic .NET and Visual C# Differences


Feature Visual Basic .NET Visual C# .NET
Case Not case sensitive: Case sensitive:
sensitive response.write("Yo") ’ OK response.write("Yo"); // Error!

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;

X = (int)Y; //Cast, OK.


Or, by using type conversion methods:
string Z;

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

span lines or be used

to comment out code. */

// Inline comments appear

// to the right of code.

/// <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

Вам также может понравиться