Net Framework Faq

54
.NET Framework Frequently Asked Questions Andy McMullan Last update: 10-Sep-2002 This FAQ tries to answer some commonly asked questions about the fundamentals of the .NET Framework. By fundamentals I mean the nuts and bolts of how the .NET Framework works at a low level - topics like assemblies, garbage collection, security, interop with COM, and remoting. The most commonly-used parts of the class library are also covered. Other aspects of the .NET Framework such as ASP.NET, ADO.NET and WinForms are not covered. This FAQ was inspired by discussions on the DOTNET mailing list. If you are not already a member of the list, you can join here: http://discuss.develop.com/dotnet.html. The list archive is also available at this address. If you have any comments, suggestions, corrections or criticisms, please e-mail me at [email protected]. If you are interested in C#, why not take a look at my C# FAQ for C++ programmers (http://www.andymcm.com/csharpfaq.htm) Disclaimer 1: The content of this FAQ is just my interpretation of information gleaned from various sources, including postings to the DOTNET mailing list and various MS documents. The answers are not necessarily completely or even partially correct. Even where the answers are correct now, they may change in the future. Disclaimer 2: This FAQ has no official connection to the DOTNET mailing list, or to Developmentor (the company who host the list), or to Microsoft. 1. Introduction 1.1 What is .NET? That's difficult to sum up in a sentence. According to Microsoft, .NET is a "revolutionary new platform, built on open Internet protocols and standards, with tools and services that meld computing and communications in new ways". A more practical definition would be that .NET is a new environment for developing and running software applications, featuring ease of development of web-based services, rich standard run-time services available to components written in a variety of programming languages, and inter-language and inter-machine interoperability. Note that when the term ".NET" is used in this FAQ it refers only to the new .NET runtime and associated technologies. This is sometimes called the ".NET Framework". This FAQ does NOT cover any of the various other existing and new products/technologies that Microsoft are attaching the .NET name to (e.g. SQL Server.NET). 1.2 Does .NET only apply to people building web-sites? No. If you write any Windows software (using ATL/COM, MFC, VB, or even raw Win32), .NET may offer a viable alternative (or addition) to the way you do things currently. Of course, if you do develop web sites, then .NET has lots to interest you - not least ASP.NET. 1.3 When was .NET announced? Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET. 1.4 When was the first version of .NET released? The final version of the 1.0 SDK and runtime was made publicly available around 6pm PST on 15-Jan-2002. At the same time, the final version of Visual Studio.NET was made available to MSDN subscribers. 1.5 What tools can I use to develop .NET applications? There are a number of tools, described here in ascending order of cost:

Transcript of Net Framework Faq

Page 1: Net Framework Faq

.NET Framework Frequently Asked Questions

Andy McMullan Last update: 10-Sep-2002 This FAQ tries to answer some commonly asked questions about the fundamentals of the .NET Framework. By fundamentals I mean the nuts and bolts of how the .NET Framework works at a low level - topics like assemblies, garbage collection, security, interop with COM, and remoting. The most commonly-used parts of the class library are also covered. Other aspects of the .NET Framework such as ASP.NET, ADO.NET and WinForms are not covered. This FAQ was inspired by discussions on the DOTNET mailing list. If you are not already a member of the list, you can join here: http://discuss.develop.com/dotnet.html. The list archive is also available at this address. If you have any comments, suggestions, corrections or criticisms, please e-mail me at [email protected]. If you are interested in C#, why not take a look at my C# FAQ for C++ programmers (http://www.andymcm.com/csharpfaq.htm) Disclaimer 1: The content of this FAQ is just my interpretation of information gleaned from various sources, including postings to the DOTNET mailing list and various MS documents. The answers are not necessarily completely or even partially correct. Even where the answers are correct now, they may change in the future. Disclaimer 2: This FAQ has no official connection to the DOTNET mailing list, or to Developmentor (the company who host the list), or to Microsoft. 1. Introduction 1.1 What is .NET?

That's difficult to sum up in a sentence. According to Microsoft, .NET is a "revolutionary new platform, built on open Internet protocols and standards, with tools and services that meld computing and communications in new ways".

A more practical definition would be that .NET is a new environment for developing and running software

applications, featuring ease of development of web-based services, rich standard run-time services available to components written in a variety of programming languages, and inter-language and inter-machine interoperability.

Note that when the term ".NET" is used in this FAQ it refers only to the new .NET runtime and associated

technologies. This is sometimes called the ".NET Framework". This FAQ does NOT cover any of the various other existing and new products/technologies that Microsoft are attaching the .NET name to (e.g. SQL Server.NET).

1.2 Does .NET only apply to people building web-sites?

No. If you write any Windows software (using ATL/COM, MFC, VB, or even raw Win32), .NET may offer a viable

alternative (or addition) to the way you do things currently. Of course, if you do develop web sites, then .NET has lots to interest you - not least ASP.NET. 1.3 When was .NET announced?

Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000

PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET. 1.4 When was the first version of .NET released?

The final version of the 1.0 SDK and runtime was made publicly available around 6pm PST on 15-Jan-2002. At

the same time, the final version of Visual Studio.NET was made available to MSDN subscribers. 1.5 What tools can I use to develop .NET applications?

There are a number of tools, described here in ascending order of cost:

Page 2: Net Framework Faq

• .NET Framework SDK: The SDK is free and includes command-line compilers for C++, C#, and VB.NET and

various other utilities to aid development.

• ASP.NET Web Matrix: This is a free ASP.NET development environment from Microsoft. As well as a GUI development environment, the download includes a simple web server that can be used instead of IIS to host ASP.NET apps. This opens up ASP.NET development to users of Windows XP Home Edition, which cannot run IIS.

• Microsoft Visual C# .NET Standard Edition: This is a cheap (around $100) version of Visual Studio limited to one language and also with limited wizard support. For example, there's no wizard support for class libraries or custom UI controls. Useful for beginners to learn with, or for savvy developers who can work around the deficiencies in the supplied wizards. As well as C#, there are VB.NET and C++ versions.

• Microsoft Visual Studio.NET Professional: If you have a license for Visual Studio 6.0, you can get the upgrade. At the time of writing (Jun 2002), Microsoft is offering a $300 mail-in rebate on the upgrade, so it's a pretty good deal. Visual Studio.NET includes support for all the MS languages (C#, C++, VB.NET) and has extensive wizard support.

At the top end of the price spectrum are the Visual Studio.NET Enterprise and Enterprise Architect editions. These offer extra features such as Visual SourceSafe (version control), and performance and analysis tools. Check out the Visual Studio.NET Feature Comparison at “http://msdn.microsoft.com/vstudio/howtobuy/choosing.asp.” 1.6 What platforms does the .NET Framework run on?

The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not

supported. Some parts of the framework do not work on all platforms - for example, ASP.NET is only supported on Windows XP and Windows 2000. Windows 98/ME cannot be used for development.

IIS is not supported on Windows XP Home Edition, and so cannot be used to host ASP.NET. However, the

ASP.NET Web Matrix web server does run on XP Home. The Mono project is attempting to implement the .NET framework on Linux.

1.7 What languages does the .NET Framework support? MS provides compilers for C#, C++, VB and JScript. Other vendors have announced that they intend to develop

.NET compilers for languages such as COBOL, Eiffel, Perl, Smalltalk and Python. 1.8 Will the .NET Framework go through a standardisation process?

From http://msdn.microsoft.com/net/ecma/: "On December 13, 2001, the ECMA General Assembly ratified the

C# and common language infrastructure (CLI) specifications into international standards. The ECMA standards will be known as ECMA-334 (C#) and ECMA-335 (the CLI)." 2. Basic terminology 2.1 What is the CLR?

CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can take advantage of, regardless of programming language. Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article:

• Object-oriented programming model (inheritance, polymorphism, exception handling, garbage collection) • Security model • Type system • All .NET base classes • Many .NET framework classes • Development, debugging, and profiling tools • Execution and code management • IL-to-native translators and optimizers

Page 3: Net Framework Faq

What this means is that in the .NET world, different programming languages will be more equal in capability than

they have ever been before, although clearly not all languages will support all CLR services. 2.2 What is the CTS? CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that

.NET applications can use. However note that not all .NET languages will support all the types in the CTS. The CTS is a superset of the CLS.

2.3 What is the CLS? CLS = Common Language Specification. This is a subset of the CTS, which all .NET languages are expected to

support. The idea is that any program which uses CLS-compliant types can interoperate with any .NET program written in any language.

In theory this allows very tight interop between different .NET languages - for example allowing a C# class to

inherit from a VB class. 2.4 What is IL? IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common

Intermediate Language). All .NET source code (of any language) is compiled to IL. The IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

2.5 What is C#? C# is a new language designed by Microsoft to work with the .NET framework. In their "Introduction to C#"

whitepaper, Microsoft describe C# as follows: "C# is a simple, modern, object oriented, and type-safe programming language derived from C and C++. C#

(pronounced “C sharp”) is firmly planted in the C and C++ family tree of languages, and will immediately be familiar to C and C++ programmers. C# aims to combine the high productivity of Visual Basic and the raw power of C++."

Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement still works pretty well :-). If you are a C++ programmer, you might like to check out my C# FAQ.(

http://www.andymcm.com/csharpfaq.htm) 2.6 What does 'managed' mean in the .NET context? The term 'managed' is the cause of much confusion. It is used in various places within .NET, meaning slightly

different things. Managed code: The .NET framework provides several core run-time services to the programs that run within it -

for example exception handling and security. For these services to work, the code must provide a minimum level of information to the runtime. Such code is called managed code. All C# and Visual Basic.NET code is managed by default. VS7 C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/com+).

Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and

VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+ switch, but it can be marked as managed using the __gc keyword.

Managed classes: This is usually referred to in the context of Managed Extensions (ME) for C++. When using

ME C++, a class can be marked with the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector, but it also means more than that. The class becomes a fully paid-up member of the .NET community with the benefits and restrictions that brings. An example of a benefit is proper interop with classes written in other languages - for example, a managed C++ class can inherit from a VB class. An example of a restriction is that a managed class can only inherit from one base class.

Page 4: Net Framework Faq

2.7 What is reflection? All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is

packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.

Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data

in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.

Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create

types dynamically at run-time (see System.Reflection.Emit.TypeBuilder). 3. Assemblies 3.1 What is an assembly? An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry

point) or a library. An assembly consists of one or more files (dlls, exes, html files etc), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.

An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the

assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET runtime sees these as two completely different types. Furthermore, don't get confused between assemblies and namespaces - namespaces are merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime.

Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at

the assembly boundary. Finally, assemblies are the unit of versioning in .NET - more on this below. 3.2 How can I produce an assembly? The simplest way to produce an assembly is directly from a .NET compiler. For example, the following C#

program: public class CTest { public CTest() { System.Console.WriteLine( "Hello from CTest" ); } }

can be compiled into a library assembly (dll) like this: csc /t:library ctest.cs You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET

SDK. Alternatively you can compile your source into modules, and then combine the modules into an assembly using

the assembly linker (al.exe). For the C# compiler, the /target:module switch is used to generate a module instead of an assembly.

3.3 What is the difference between a private assembly and a shared assembly?

• Location and visibility: A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache,

Page 5: Net Framework Faq

which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. the .NET framework classes.

• Versioning: The runtime enforces versioning constraints only on shared assemblies, not on private assemblies.

3.4 How do assemblies find each other? By searching directory paths. There are several factors which can affect the path (such as the AppDomain host,

and application configuration files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache.

3.5 How does assembly versioning work? Each assembly has a version number called the compatibility version. Also each reference to an assembly (from

another assembly) includes both the name and version of the referenced assembly. The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different

are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file.

Remember: versioning is only applied to shared assemblies, not private assemblies. 4. Application Domains 4.1 What is an Application Domain? An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32

process. The primary purpose of the AppDomain is to isolate an application from other applications. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is

expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory.

4.2 How does an AppDomain get created? AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When

you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application.

AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an

AppDomain, creates an instance of an object inside it, and then executes one of the object's methods. Note that you must name the executable 'appdomaintest.exe' for this code to work as-is.

using System; using System.Runtime.Remoting; public class CAppDomainInfo : MarshalByRefObject { public string GetAppDomainInfo() { return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName; } }

Page 6: Net Framework Faq

public class App { public static int Main() { AppDomain ad = AppDomain.CreateDomain( "Andy's new domain", null, null ); ObjectHandle oh = ad.CreateInstance( "appdomaintest", "CAppDomainInfo" ); CAppDomainInfo adInfo = (CAppDomainInfo)(oh.Unwrap()); string info = adInfo.GetAppDomainInfo(); Console.WriteLine( "AppDomain info: " + info ); return 0; } } 4.3 Can I write my own .NET host? Yes. For an example of how to do this, take a look at the source for the dm.net moniker developed by Jason

Whittington and Don Box (http://staff.develop.com/jasonw/clr/readme.htm ). There is also a code sample in the .NET SDK called CorHost.

5. Garbage Collection 5.1 What is garbage collection? Garbage collection is a system whereby a run-time component takes responsibility for managing the lifetime of

objects and the heap memory that they occupy. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.

5.2 Is it true that objects don't always get destroyed immediately when the last reference goes

away? Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory

reclaimed. There is an interesting thread in the archives, started by Chris Sells, about the implications of non-deterministic

destruction of objects in C#: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R24819 In October 2000, Microsoft's Brian Harry posted a lengthy analysis of the problem:

http://discuss.develop.com/archives/wa.exe?A2=ind0010A&L=DOTNET&P=R28572 Chris Sells' response to Brian's posting is here:

http://discuss.develop.com/archives/wa.exe?A2=ind0010C&L=DOTNET&P=R983 5.3 Why doesn't the .NET runtime offer deterministic destruction? Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a

list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next sweep of the heap.

Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible.

Normally heap exhaustion is the trigger for a collection sweep. 5.4 Is the lack of deterministic destruction in .NET a problem? It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce

resources (e.g. database locks), you need to provide some way for the client to tell the object to release the resource when it is done. Microsoft recommend that you provide a method called Dispose() for this purpose. However, this causes problems for distributed objects - in a distributed system who calls the Dispose() method? Some form of

Page 7: Net Framework Faq

reference-counting or ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this.

5.5 Does non-deterministic destruction affect the usage of COM objects from managed code? Yes. When using a COM object from managed code, you are effectively relying on the garbage collector to call

the final release on your object. If your COM object holds onto an expensive resource which is only cleaned-up after the final release, you may need to provide a new interface on your object which supports an explicit Dispose() method.

5.6 I've heard that Finalize methods should be avoided. Should I implement Finalize on my

class? An object with a Finalize method is more work for the garbage collector than an object without one. Also there

are no guarantees about the order in which objects are Finalized, so there are issues surrounding access to other objects from the Finalize method. Finally, there is no guarantee that a Finalize method will get called on an object, so it should never be relied upon to do clean-up of an object's resources.

Microsoft recommend the following pattern: public class CTest : IDisposable { public void Dispose() { ... // Cleanup activities GC.SuppressFinalize(this); } ~CTest() // C# syntax hiding the Finalize() method { Dispose(); } } In the normal case the client calls Dispose(), the object's resources are freed, and the garbage collector is

relieved of its Finalizing duties by the call to SuppressFinalize(). In the worst case, i.e. the client forgets to call Dispose(), there is a reasonable chance that the object's resources will eventually get freed by the garbage collector calling Finalize(). Given the limitations of the garbage collection algorithm this seems like a pretty reasonable approach.

5.7 Do I have any control over the garbage collection algorithm? A little. For example, the System.GC class exposes a Collect method - this forces the garbage collector to collect

all unreferenced objects immediately. 5.8 How can I find out what the garbage collector is doing? Lots of interesting statistics are exported from the .NET runtime via the '.NET CLR xxx' performance counters.

Use Performance Monitor to view them. 6. Serialization 6.1 What is serialization? Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process

of creating an object from a stream of bytes. Serialization/Deserialization is mostly used to transport objects (e.g. during remoting), or to persist objects (e.g. to a file or database).

Page 8: Net Framework Faq

6.2 Does the .NET Framework have in-built support for serialization? There are two separate mechanisms provided by the .NET class library - XmlSerializer and

SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

6.3 I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or

BinaryFormatter? It depends. XmlSerializer has severe limitations such as the requirement that the target class has a

parameterless constructor, and only public read/write properties and fields can be serialized. However, on the plus side, XmlSerializer has good support for customising the XML document that is produced or consumed. XmlSerializer's features mean that it is most suitable for cross-platform work, or for constructing objects from existing XML documents.

SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can serialize private fields,

for example. However they both require that the target class be marked with the [Serializable] attribute, so like XmlSerializer the class needs to be written with serialization in mind. Also there are some quirks to watch out for - for example on deserialization the constructor of the new object is not invoked.

The choice between SoapFormatter and BinaryFormatter depends on the application. BinaryFormatter makes

sense where both serialization and deserialization will be performed on the .NET platform and where performance is important. SoapFormatter generally makes more sense in all other cases, for ease of debugging if nothing else.

6.4 Can I customise the serialization process? Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class.

For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement] attribute, which can be used to specify the XML element name to be used for a particular property or field.

Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For

example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized.

6.5 Why is XmlSerializer so slow? There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize

an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

6.6 Why do I get errors when I try to serialize a Hashtable? XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable.

SoapFormatter and BinaryFormatter do not have this restriction. 6.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I

find out what the problem is? Look at the InnerException property of the exception that is thrown to get a more specific error message. 7. Attributes 7.1 What are attributes? There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some

data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be attached to a class and means that instances of the class can be serialized.

Page 9: Net Framework Faq

[serializable] public class CTest {} The other type of attribute is a context attribute. Context attributes use a similar syntax to metadata attributes but

they are fundamentally different. Context attributes provide an interception mechanism whereby instance activation and method calls can be pre- and/or post-processed. If you've come across Keith Brown's universal delegator you'll be familiar with this idea.

7.2 Can I create my own metadata attributes? Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example: [AttributeUsage(AttributeTargets.Class)] public class InspiredByAttribute : System.Attribute { public string InspiredBy; public InspiredByAttribute( string inspiredBy ) { InspiredBy = inspiredBy; } } [InspiredBy("Andy Mc's brilliant .NET FAQ")] class CTest { } class CApp { public static void Main() { object[] atts = typeof(CTest).GetCustomAttributes(true); foreach( object att in atts ) if( att is InspiredByAttribute ) Console.WriteLine( "Class CTest was inspired by {0}",

((InspiredByAttribute)att).InspiredBy ); } } 7.3 Can I create my own context attributes? Yes. Take a look at Don Box's sample (called CallThreshold) at http://www.develop.com/dbox/dotnet/threshold/,

and also Peter Drayton's Tracehook.NET at http://www.razorsoft.net/ 8. Code Access Security 8.1 What is Code Access Security (CAS)? CAS is the part of the .NET security model that determines whether or not a piece of code is allowed to run, and

what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.

8.2 How does CAS work? The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly

is a member of a particular code group, and each code group is granted the permissions specified in a named permission set.

Page 10: Net Framework Faq

For example, using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group, which adheres to the permissions defined by the 'Internet' named permission set. (Naturally the 'Internet' named permission set represents a very restrictive range of permissions.)

8.3 Who defines the CAS code groups? Microsoft defines some default ones, but you can modify these and even create your own. To see the code

groups defined on your system, run 'caspol -lg' from the command-line. On my system it looks like this: Level = Machine Code Groups: 1. All code: Nothing 1.1. Zone - MyComputer: FullTrust 1.1.1. Honor SkipVerification requests: SkipVerification 1.2. Zone - Intranet: LocalIntranet 1.3. Zone - Internet: Internet 1.4. Zone - Untrusted: Nothing 1.5. Zone - Trusted: Internet 1.6. StrongName - 0024000004800000940000000602000000240000525341310004000003 000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348E

BD06 F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B

465E08 07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561A

ABF5C AC1DF1734633C602F8F2D5: Everything Note the hierarchy of code groups - the top of the hierarchy is the most general ('All code'), which is then sub-

divided into several groups, each of which in turn can be sub-divided. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission set than its parent.

8.4 How do I define my own code group? Use caspol. For example, suppose you trust code from www.mydomain.com and you want it have full access to

your system, but you want to keep the default restrictions for all other internet sites. To achieve this, you would add a new code group as a sub-group of the 'Zone - Internet' group, like this:

caspol -ag 1.3 -site www.mydomain.com FullTrust Now if you run caspol -lg you will see that the new group has been added as group 1.3.1: ... 1.3. Zone - Internet: Internet 1.3.1. Site - www.mydomain.com: FullTrust ... Note that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to manipulate from

the command-line. The underlying runtime never sees it. 8.5 How do I change the permission set for a code group? Use caspol. If you are the machine administrator, you can operate at the 'machine' level - which means not only

that the changes you make become the default for the machine, but also that users cannot change the permissions to be more permissive. If you are a normal (non-admin) user you can still modify the permissions, but only to make them more restrictive. For example, to allow intranet code to do what it likes you might do this:

caspol -cg 1.2 FullTrust

Page 11: Net Framework Faq

Note that because this is more permissive than the default policy (on a standard system), you should only do this at the machine level - doing it at the user level will have no effect.

8.6 Can I create my own permission set? Yes. Use caspol -ap, specifying an XML file containing the permissions in the permission set. To save you some

time, here is a sample file corresponding to the 'Everything' permission set - just edit to suit your needs. When you have edited the sample, add it to the range of available permission sets like this:

caspol -ap samplepermset.xml Then, to apply the permission set to a code group, do something like this: caspol -cg 1.3 SamplePermSet (By default, 1.3 is the 'Internet' code group) 8.7 I'm having some trouble with CAS. How can I diagnose my problem? Caspol has a couple of options that might help. First, you can ask caspol to tell you what code group an

assembly belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a particular assembly using caspol -rsp.

8.8 I can't be bothered with all this CAS stuff. Can I turn it off? Yes, as long as you are an administrator. Just run: caspol -s off 9. Intermediate Language (IL) 9.1 Can I look at the IL for an assembly? Yes. MS supply a tool called Ildasm which can be used to view the metadata and IL for an assembly. 9.2 Can source code be reverse-engineered from IL? Yes, it is often relatively straightforward to regenerate high-level source (e.g. C#) from IL. 9.3 How can I stop my code being reverse-engineered from IL? There is currently no simple way to stop code being reverse-engineered from IL. In future it is likely that IL

obfuscation tools will become available, either from MS or from third parties. These tools work by 'optimising' the IL in such a way that reverse-engineering becomes much more difficult.

Of course if you are writing web services then reverse-engineering is not a problem as clients do not have

access to your IL. 9.4 Can I write IL programs directly? Yes. Peter Drayton posted this simple example to the DOTNET mailing list: .assembly MyAssembly {} .class MyApp { .method static void Main() { .entrypoint ldstr "Hello, IL!" call void System.Console::WriteLine(class System.Object) ret } } Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.

Page 12: Net Framework Faq

9.5 Can I do things in IL that I can't do in C#? Yes. A couple of simple examples are that you can throw exceptions that are not derived from

System.Exception, and you can have non-zero-based arrays. 10. Implications for COM 10.1 Is COM dead? This subject causes a lot of controversy, as you'll see if you read the mailing list archives. Take a look at the

following two threads: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D=0&P=68241

http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R60761 FWIW my view is as follows: COM is many things, and it's different things to different people. But to me, COM is

fundamentally about how little blobs of code find other little blobs of code, and how they communicate with each other when they find each other. COM specifies precisely how this location and communication takes place. In a 'pure' .NET world, consisting entirely of .NET objects, little blobs of code still find each other and talk to each other, but they don't use COM to do so. They use a model which is similar to COM in some ways - for example, type information is stored in a tabular form packaged with the component, which is quite similar to packaging a type library with a COM component. But it's not COM.

So, does this matter? Well, I don't really care about most of the COM stuff going away - I don't care that finding

components doesn't involve a trip to the registry, or that I don't use IDL to define my interfaces. But there is one thing that I wouldn't like to go away - I wouldn't like to lose the idea of interface-based development. COM's greatest strength, in my opinion, is its insistence on a cast-iron separation between interface and implementation. Unfortunately, the .NET framework seems to make no such insistence - it lets you do interface-based development, but it doesn't insist. Some people would argue that having a choice can never be a bad thing, and maybe they're right, but I can't help feeling that maybe it's a backward step.

10.2 Is DCOM dead? Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on

DCOM. Of course DCOM will still be used in interop scenarios. 10.3 Is MTS/COM+ dead? No. The approach for the first .NET release is to provide access to the existing COM+ services (through an

interop layer) rather than replace the services with native .NET ones. Various tools and attributes are provided to try to make this as painless as possible. The PDC release of the .NET SDK includes interop support for core services (JIT activation, transactions) but not some of the higher level services (e.g. COM+ Events, Queued components).

Over time it is expected that interop will become more seamless - this may mean that some services become a

core part of the CLR, and/or it may mean that some services will be rewritten as managed code which runs on top of the CLR.

For more on this topic, search for postings by Joe Long in the archives - Joe is the MS group manager for

COM+. Start with this message: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R68370 10.4 Can I use COM components from .NET programs? Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This

wrapper turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to .NET-compatible types.

Page 13: Net Framework Faq

Here's a simple example for those familiar with ATL. First, create an ATL component which implements the following IDL:

import "oaidl.idl"; import "ocidl.idl"; [ object, uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206), helpstring("ICppName Interface"), pointer_default(unique), oleautomation ] interface ICppName : IUnknown { [helpstring("method SetName")] HRESULT SetName([in] BSTR name); [helpstring("method GetName")] HRESULT GetName([out,retval] BSTR *pName ); }; [ uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D), version(1.0), helpstring("cppcomserver 1.0 Type Library") ] library CPPCOMSERVERLib { importlib("stdole32.tlb"); importlib("stdole2.tlb"); [ uuid(600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70), helpstring("CppName Class") ] coclass CppName { [default] interface ICppName; }; }; When you've built the component, you should get a typelibrary. Run the TLBIMP utility on the typelibary, like this: tlbimp cppcomserver.tlb If successful, you will get a message like this: Typelib imported successfully to CPPCOMSERVERLib.dll You now need a .NET client - let's use C#. Create a .cs file containing the following code: using System; using CPPCOMSERVERLib; public class MainApp { static public void Main() { CppName cppname = new CppName(); cppname.SetName( "bob" );

Page 14: Net Framework Faq

Console.WriteLine( "Name is " + cppname.GetName() ); } } Note that we are using the type library name as a namespace, and the COM class name as the class.

Alternatively we could have used CPPCOMSERVERLib.CppName for the class name and gone without the using CPPCOMSERVERLib statement.

Compile the C# code like this: csc /r:cppcomserverlib.dll csharpcomclient.cs Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using

TLBIMP. You should now be able to run csharpcomclient.exe, and get the following output on the console: Name is bob 10.5 Can I use .NET components from COM programs? Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW

(see previous question), but works in the opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW can be developed. Also, for COM to 'see' the .NET component, the .NET component must be registered in the registry.

Here's a simple example. Create a C# file called testcomserver.cs and put the following in it: using System; namespace AndyMc { public class CSharpCOMServer { public CSharpCOMServer() {} public void SetName( string name ) { m_name = name; } public string GetName() { return m_name; } private string m_name; } } Then compile the .cs file as follows: csc /target:library testcomserver.cs You should get a dll, which you register like this: regasm testcomserver.dll /tlb:testcomserver.tlb /codebase Now you need to create a client to test your .NET COM component. VBScript will do - put the following in a file

called comclient.vbs: Dim dotNetObj Set dotNetObj = CreateObject("AndyMc.CSharpCOMServer") dotNetObj.SetName ("bob") MsgBox "Name is " & dotNetObj.GetName() and run the script like this: wscript comclient.vbs And hey presto you should get a message box displayed with the text "Name is bob". An alternative to the approach above it to use the dm.net moniker developed by Jason Whittington and Don Box.

Go to http://staff.develop.com/jasonw/clr/readme.htm to check it out.

Page 15: Net Framework Faq

10.6 Is ATL redundant in the .NET world? Yes, if you are writing applications that live inside the .NET framework. Of course many developers may wish to

continue using ATL to write C++ COM components that live outside the framework, but if you are inside you will almost certainly want to use C#. Raw C++ (and therefore ATL which is based on it) doesn't have much of a place in the .NET world - it's just too near the metal and provides too much flexibility for the runtime to be able to manage it.

11. Miscellaneous 11.1 How does .NET remoting work? .NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP.

TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet). Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By

default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format.

There are a number of styles of remote access: • SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown away when

the request has finished. This (essentially stateless) model can be made stateful in the ASP.NET environment by using the ASP.NET state service to store application or session state.

• Singleton. All incoming requests from clients are processed by a single server object.

• Client-activated object. This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it.

Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has

a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure. Objects have a default renew time - the lease is renewed when a successful call is made from the client to the object. The client can also explicitly renew the lease.

If you're interested in using XML-RPC as an alternative to SOAP, take a look at Charles Cook's XML-RPC.Net

site at http://www.cookcomputing.com/xmlrpc/xmlrpc.shtml. 11.2 How can I get at the Win32 API from a .NET program? Use P/Invoke. This uses similar technology to COM Interop, but is used to access static DLL entry points instead

of COM objects. Here is an example of C# calling the Win32 MessageBox function: using System; using System.Runtime.InteropServices; class MainApp { [DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true, CharSet=CharSet.Auto)] public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType); public static void Main() { MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 ); } }

Page 16: Net Framework Faq

12. Class Library 12.1 File I/O 12.1.1 How do I read from a text file? First, use a System.IO.FileStream object to open the file: FileStream fs = new FileStream( @"c:\test.txt", FileMode.Open, FileAccess.Read ); FileStream inherits from Stream, so you can wrap the FileStream object with a StreamReader object. This

provides a nice interface for processing the stream line by line: StreamReader sr = new StreamReader( fs ); string curLine; while( (curLine = sr.ReadLine()) != null ) Console.WriteLine( curLine ); Finally close the StreamReader object: sr.Close(); Note that this will automatically call Close() on the underlying Stream object, so an explicit fs.Close() is not

required. 12.1.2 How do I write to a text file? Similar to the read example, except use StreamWriter instead of StreamReader. 12.1.3 How do I read/write binary files? Similar to text files, except wrap the FileStream object with a BinaryReader/Writer object instead of a

StreamReader/Writer object. 12.1.4 How do I delete a file? Use the static Delete() method on the System.IO.File object: File.Delete( @"c:\test.txt" ); 12.2 Text Processing 12.2.1 Are regular expressions supported? Yes. Use the System.Text.RegularExpressions.Regex class. For example, the following code updates the title in

an HTML file: FileStream fs = new FileStream( "test.htm", FileMode.Open, FileAccess.Read ); StreamReader sr = new StreamReader( fs ); Regex r = new Regex( "<TITLE>(.*)</TITLE>" ); string s; while( (s = sr.ReadLine()) != null ) { if( r.IsMatch( s ) ) s = r.Replace( s, "<TITLE>New and improved ${1}</TITLE>" ); Console.WriteLine( s ); }

Page 17: Net Framework Faq

12.3 Internet 12.3.1 How do I download a web page? First use the System.Net.WebRequestFactory class to acquire a WebRequest object: WebRequest request = WebRequest.Create( "http://localhost" ); Then ask for the response from the request: WebResponse response = request.GetResponse(); The GetResponse method blocks until the download is complete. Then you can access the response stream like

this: Stream s = response.GetResponseStream(); // Output the downloaded stream to the console StreamReader sr = new StreamReader( s ); string line; while( (line = sr.ReadLine()) != null ) Console.WriteLine( line ); Note that WebRequest and WebReponse objects can be downcast to HttpWebRequest and HttpWebReponse

objects respectively, to access http-specific functionality. 12.3.2 How do I use a proxy? Two approaches - to affect all web requests do this: System.Net.GlobalProxySelection.Select = new WebProxy( "proxyname", 80 ); Alternatively, to set the proxy for a specific web request, do this: HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://localhost" ); request.Proxy = new WebProxy( "proxyname", 80 ); 12.4 XML 12.4.1 Is DOM supported? Yes. Take this example XML document: <PEOPLE> <PERSON>Fred</PERSON> <PERSON>Bill</PERSON> </PEOPLE> This document can be parsed as follows: XmlDocument doc = new XmlDocument(); doc.Load( "test.xml" ); XmlNode root = doc.DocumentElement; foreach( XmlNode personElement in root.ChildNodes ) Console.WriteLine( personElement.FirstChild.Value.ToString() ); The output is: Fred Bill 12.4.2 Is SAX supported? No. Instead, a new XmlReader/XmlWriter API is offered. Like SAX it is stream-based but it uses a 'pull' model

rather than SAX's 'push' model. Here's an example: XmlTextReader reader = new XmlTextReader( "test.xml" );

Page 18: Net Framework Faq

while( reader.Read() ) { if( reader.NodeType == XmlNodeType.Element && reader.Name == "PERSON" ) { reader.Read(); // Skip to the child text Console.WriteLine( reader.Value ); } } 12.4.3 Is XPath supported? Yes, via the XPathXXX classes: XPathDocument xpdoc = new XPathDocument("test.xml"); XPathNavigator nav = xpdoc.CreateNavigator(); XPathExpression expr = nav.Compile("descendant::PEOPLE/PERSON"); XPathNodeIterator iterator = nav.Select(expr); while (iterator.MoveNext()) Console.WriteLine(iterator.Current); 12.5 Threading 12.5.1 Is multi-threading supported? Yes, there is extensive support for multi-threading. New threads can be spawned, and there is a system-

provided threadpool which applications can use. 12.5.2 How do I spawn a thread? Create an instance of a System.Threading.Thread object, passing it an instance of a ThreadStart delegate that

will be executed on the new thread. For example: class MyThread { public MyThread( string initData ) { m_data = initData; m_thread = new Thread( new ThreadStart(ThreadMain) ); m_thread.Start(); } // ThreadMain() is executed on the new thread. private void ThreadMain() { Console.WriteLine( m_data ); } public void WaitUntilFinished() { m_thread.Join(); } private Thread m_thread; private string m_data; }

Page 19: Net Framework Faq

In this case creating an instance of the MyThread class is sufficient to spawn the thread and execute the

MyThread.ThreadMain() method: MyThread t = new MyThread( "Hello, world." ); t.WaitUntilFinished(); 12.5.3 How do I stop a thread? There are several options. First, you can use your own communication mechanism to tell the ThreadStart

method to finish. Alternatively the Thread class has in-built support for instructing the thread to stop. The two principle methods are Thread.Interrupt() and Thread.Abort(). The former will cause a ThreadInterruptedException to be thrown on the thread when it next goes into a WaitJoinSleep state. In other words, Thread.Interrupt is a polite way of asking the thread to stop when it is no longer doing any useful work. In contrast, Thread.Abort() throws a ThreadAbortException regardless of what the thread is doing. Furthermore, the ThreadAbortException cannot normally be caught (though the ThreadStart's finally method will be executed). Thread.Abort() is a heavy-handed mechanism which should not normally be required.

12.5.4 How do I use the thread pool? By passing an instance of a WaitCallback delegate to the ThreadPool.QueueUserWorkItem() method: class CApp { static void Main() { string s = "Hello, World"; ThreadPool.QueueUserWorkItem( new WaitCallback( DoWork ), s ); Thread.Sleep( 1000 ); // Give time for work item to be executed } // DoWork is executed on a thread from the thread pool. static void DoWork( object state ) { Console.WriteLine( state ); } } 12.5.5 How do I know when my thread pool work item has completed? There is no way to query the thread pool for this information. You must put code into the WaitCallback method to

signal that it has completed. Events are useful for this. 12.5.6 How do I prevent concurrent access to my data? Each object has a concurrency lock (critical section) associated with it. The System.Threading.Monitor.Enter/Exit

methods are used to acquire and release this lock. For example, instances of the following class only allow one thread at a time to enter method f():

class C { public void f() { try { Monitor.Enter(this); ... } finally

Page 20: Net Framework Faq

{ Monitor.Exit(this); } } } C# has a 'lock' keyword which provides a convenient shorthand for the code above: class C { public void f() { lock(this) { ... } } } Note that calling Monitor.Enter(myObject) does NOT mean that all access to myObject is serialized. It means

that the synchronisation lock associated with myObject has been acquired, and no other thread can acquire that lock until Monitor.Exit(o) is called. In other words, this class is functionally equivalent to the classes above:

class C { public void f() { lock( m_object ) { ... } } private m_object = new object(); } 12.6 Tracing 12.6.1 Is there built-in support for tracing/logging? Yes, in the System.Diagnostics namespace. There are two main classes that deal with tracing - Debug and

Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.

12.6.2 Can I redirect tracing to a file? Yes. The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the

tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose.

Here's how to use the TextWriterTraceListener class to redirect Trace output to a file: Trace.Listeners.Clear(); FileStream fs = new FileStream( @"c:\log.txt", FileMode.Create, FileAccess.Write ); Trace.Listeners.Add( new TextWriterTraceListener( fs ) ); Trace.WriteLine( @"This will be writen to c:\log.txt!" );

Page 21: Net Framework Faq

Trace.Flush(); Note the use of Trace.Listeners.Clear() to remove the default listener. If you don't do this, the output will go to

the file and OutputDebugString(). Typically this is not what you want, because OutputDebugString() imposes a big performance hit.

12.6.3 Can I customise the trace output? Yes. You can write your own TraceListener-derived class, and direct all output through it. Here's a simple

example, which derives from TextWriterTraceListener (and therefore has in-built support for writing to files, as shown above) and adds timing information and the thread ID for each trace line:

class MyListener : TextWriterTraceListener { public MyListener( Stream s ) : base(s) { } public override void WriteLine( string s ) { Writer.WriteLine( "{0:D8} [{1:D4}] {2}", Environment.TickCount - m_startTickCount, AppDomain.GetCurrentThreadId(), s ); } protected int m_startTickCount = Environment.TickCount; } (Note that this implementation is not complete - the TraceListener.Write method is not overridden for example.) The beauty of this approach is that when an instance of MyListener is added to the Trace.Listeners collection, all

calls to Trace.WriteLine() go through MyListener, including calls made by referenced assemblies that know nothing about the MyListener class.

13. Resources 13.1 Recommended books I recommend the following books, either because I personally like them, or because I think they are well

regarded by other .NET developers. (Note that I get a commission from Amazon if you buy a book after following one of these links.)

• Applied Microsoft .NET Framework Programming - Jeffrey Richter Much anticipated, mainly due to Richter's superb Win32 books, and most people think it delivers. The 'applied' is a little misleading - this book is mostly about how the .NET Framework works 'under the hood'. Examples are in C#, but there is also a separate VB edition of the book.

• Programming Windows with C# - Charles Petzold Another slightly misleading title - this book is solely about GUI programming - Windows Forms and GDI+. Well written, with comprehensive coverage. My only (minor) criticism is that the book sticks closely to the facts, without offering a great deal in the way of 'tips and tricks' for real-world apps.

• Developing Applications with Visual Studio.NET - Richard Grimes Covers lots of interesting topics that other books don't, including ATL7, Managed C++, internationalization, remoting, as well as the more run-of-the-mill CLR and C# stuff. Also a lot of info on the Visual Studio IDE. This book is most suitable for reasonably experienced C++ programmers.

• C# and the .NET Platform - Andrew Troelsen Regarded by many as the best all round C#/.NET book. Wide coverage including Windows Forms, COM interop, ADO.NET, ASP.NET etc. Troelsen also has a respected VB.NET

Page 22: Net Framework Faq

book called Visual Basic .NET and the .NET Platform: An Advanced Guide.

• Programming Microsoft Visual Basic .NET - Francesco Balena Balena is a reknowned VB-er, and the reviews of his VB.NET book are glowing.

• .NET and COM - The Complete Interoperability Guide - Adam Nathan Widely regarded as the bible of .NET/COM interop.

• Advanced .NET Remoting - Ingo Rammer Widely recommended.

13.2 Internet Resources

• The Microsoft .NET homepage is at http://www.microsoft.com/net/. Microsoft also host GOTDOTNET. • DevX host the .NET Zone. • http://www.cetus-links.org/oo_dotnet.html is a superb set of links to .NET resources. • Chris Sells has a great set of .NET links at http://www.sellsbrothers.com/links/#manlinks. • CSharp.org • microsoft.public.dotnet.* newsgroups • My C# FAQ for C++ Programmers. 13.3 Weblogs The following Weblogs have regular .NET content: • The .NET Guy (Brad Wilson) • Charles Cook: Developer of XML-RPC.NET. • John Lam • Peter Drayton: Co-author of "C# Essentials" and "C# in a Nutshell". • Ingo Rammer: Author of "Advanced .NET remoting". • Drew Marsh • Tomas Restrepo • Justin Rudd • Simon Fell: Developer of PocketSOAP. • Richard Caetano • sellsbrothers.com: Windows Developer News: Not really a blog, but includes regular .NET-related news. 13.4 Sample code & utilities Lutz Roeder has some great utilities and libraries at http://www.aisto.com/roeder/dotnet/ Peter Drayton's .NET Goodies page is at http://www.razorsoft.net/ Don Box & Jason Whittington's dm.net COM moniker at http://staff.develop.com/jasonw/clr/readme.htm Mike Woodring has some .NET samples at http://staff.develop.com/woodring/dotnet/ Charles Cook's XML-RPC.Net library is available at http://www.cookcomputing.com/.

Question: Is it true that COM objects no longer need to be registered on the server? Answer: Yes and No. Legacy COM objects still need to be registered on the server before they can be used. COM developed using the new .NET Framework will not need to be registered. Developers will be able to auto-register these objects just by placing them in the 'bin' folder of the application. Question: Can .NET Framework components use the features of Component Services?

Answer: Yes, you can use the features and functions of Component Services from a .NET Framework component.

Page 23: Net Framework Faq

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 %> This often corrects the error. If you are curious, there is another FAQ on what this line actually does.

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

Question: Where can I find a shareware ASP.Net editor?

Answer: ASP Express Version 1.92 supports ASP.Net

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

Page 24: Net Framework Faq

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. The client-side technology to easily create these types of client controls in .NET is called "WinForms" and lives within the System.WinForms code namespace. It has built-in designer support within Visual Studio.NET. More details on how to use .NET Client Controls within a browser can be found in this article: http://www.gotdotnet.com/team/windowsforms/iesourcing.aspx Charles Carroll has kindly setup a set of WinForms specific listservs that you can join from: http://www.asplists.com/asplists/winforms.asp. They'll provide a great forum for discussing winforms.

Question: Is there a summary of differences from ASP to ASP.Net?

Answer: http://www.aspng.com/learn/differences.aspx is a starting point. Question: What happened to date() and time()?

Page 25: Net Framework Faq

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: Are there resources online with tips on ASP to ASP.Net conversions? Answer: Here are a couple: http://home.earthlink.net/~butlerbob/VBNet.htm http://www.asptoday.com/articles/20000914.htm http://www.4guysfromrolla.com/webtech/091500-1.shtml http://www.asptoday.com/articles/20000712.htm http://www.plusasp.com/plusasp/converting.aspx Question: How do I subtract days from a date and display it? Answer: 'Try:

Page 26: Net Framework Faq

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 What platforms does ASP.NET run on? Currently, it's supported on Windows 2000 and Windows XP. ASP.NET integrates with Internet Information Server (IIS) and thus requires that IIS be installed. It runs on server and non-server editions of Windows 2000 and XP as long as IIS is installed. Microsoft originally planned to support ASP.NET on Windows NT 4.0, but had to reconsider due to time and technical constraints. Can two different programming languages be mixed in a single ASPX file? No. ASP.NET uses parsers to strip the code from ASPX files and copy it to temporary files containing derived Page classes, and a given parser understands only one language. Why can't I put <%@ Page Language="C++" %> at the top of an ASPX file and write my server-side scripts in C++? Because the parsers ASP.NET uses to extract code from ASPX files only understand C#, Visual Basic.NET, and JScript.NET. However, if you use code-behind to get your code out of the ASPX file and into a separately compiled source code file. You can write server-side scripts in any language supported by a .NET compiler. Can I use code-behind with Global.asax files?

Yes. Here's a simple Global.asax file that doesn't use code-behind:

<%@ Import Namespace="System.Data" %> <script language="C#" runat="server"> void Application_Start () { DataSet ds = new DataSet (); ds.ReadXml (Server.MapPath ("GlobalData.xml")); Application["GlobalData"] = ds; } </script>

Here's the equivalent file written to use code-behind:

<%@ Application Inherits="MyApp" %>

And here's the MyApp class that it references:

Using System.Web; using System.Data; public class MyApp : HttpApplication { public void Application_Start () {

Page 27: Net Framework Faq

DataSet ds = new DataSet (); ds.ReadXml ("GlobalData.xml"); Application["GlobalData"] = ds; } }

So that ASP.NET can find the MyApp class, compile it into a DLL (csc /t:library filename.cs) and place it in the application root's bin subdirectory. Can you override method="post" in a <form runat="server"> tag by writing <form method="get" runat="server">? Yes. Can a Web form post back to a form other than itself?

No. Even if you try to change the target of the postback by including an action attribute in the <form> tag, ASP.NET will override it and force the form to post back to itself. To jump to another page after a postback occurs, use Response.Redirect or Server.Transfer. Can an ASPX file contain more than one form marked runat="server"?

No. Is it possible to see the code that ASP.NET generates from an ASPX file? Yes. Enable debugging by including a <%@ Page Debug="true" %> directive in the ASPX file or a <compilation debug="true"> statement in Web.config. Then look for the generated CS or VB file in a subdirectory underneath \%SystemRoot%\Microsoft.NET\Framework\v1.0.nnnn\Temporary ASP.NET Files. Does ASP.NET support server-side includes? Yes. Server-side includes work the same in ASP.NET as they do in ASP. Does ASP.NET support server-side object tags? Yes. The following tag creates an instance of a custom type named ShoppingCart and assigns it session scope (that is, it creates a unique ShoppingCart instance for each and every session created on the server):

<object id="MyShoppingCart" class="ShoppingCart" scope="session" runat="server" />

Managed types created this way are identified by class name. Unmanaged types (COM classes) are identified by CLSID or ProgID.

How do I comment out statements in ASPX files?

<%-- <asp:Button Text="Click Me" OnClick="OnClick" runat="server" /> --%>

Can I use custom .NET data types in a Web form?

Yes. Place the DLL containing the type in the application root's bin directory and ASP.NET will automatically load the DLL when the type is referenced. How do I debug an ASP.NET application that wasn't written with Visual Studio.NET and that doesn't use code-behind?

Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing the code you want to debug, and set your breakpoints. Start the ASP.NET application. Go back to DbgClr, choose Debug Processes from the Tools menu, and select aspnet_wp.exe from the list of processes. (If aspnet_wp.exe doesn't appear in the list, check the "Show system processes" box.) Click the Attach button to attach to aspnet_wp.exe and begin debugging.Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can enable tell ASP.NET to build debug executables by placing a

<%@ Page Debug="true" %>

Page 28: Net Framework Faq

statement at the top of an ASPX file or a

<compilation debug="true" />

statement in a Web.config file. What event handlers can I include in Global.asax?

Application start and end event handlers

• Application_Start • Application_End

Session start and end event handlers

• Session_Start • Session_End

Per-request event handlers (listed in the order in which they're called)

• Application_BeginRequest • Application_AuthenticateRequest • Application_AuthorizeRequest • Application_ResolveRequestCache • Application_AcquireRequestState • Application_PreRequestHandlerExecute • Application_PostRequestHandlerExecute • Application_ReleaseRequestState • Application_UpdateRequestCache • Application_EndRequest

Non-deterministic event handlers

• Application_Error • Application_Disposed

Global.asax can also include handlers for events fired by custom HTTP modules. The event handlers listed above are intrinsic to ASP.NET. Is it possible to protect view state from tampering when it's passed over an unencrypted channel?

Yes. Simply include an @ Page directive with an EnableViewStateMac="true" attribute in each ASPX file you wish to protect, or include the following statement in Web.config:

<pages enableViewStateMac="true" />

This configuration directive appends a hash (officially called the message authentication code, or MAC) to view state values round-tripped to the client and enables ASP.NET to detect altered view state. If ASP.NET determines that view state has been altered when a page posts back to the server, it throws an exception.The hash is generated by appending a secret key (the validationKey value attached to the <machineKey> element in Machine.config) to the view state and hashing the result. An attacker can't modify view state and fix up the hash without knowing the secret key, too. Is it possible to encrypt view state when it's passed over an unencrypted channel?

Page 29: Net Framework Faq

Yes. Add the following statement to Web.config:

<machineKey validation="3DES" /> Can a user browsing my Web site read my Web.config or Global.asax files?

No. The <httpHandlers> section of Machine.config, which holds the master configuration settings for ASP.NET, contains entries that map ASAX files, CONFIG files, and selected other file types to an HTTP handler named HttpForbiddenHandler, which fails attempts to retrieve the associated file. Here are the relevant statements in Machine.config:

<add verb="*" path="*.asax" type="System.Web.HttpForbiddenHandler, ... /> <add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler, ... />

Do Web controls support Cascading Style Sheets?

Yes. All Web controls inherit a property named CssClass from the base class System.Web.UI.WebControls.WebControl. The following example defines a CSS class named Input and uses it to modify a TextBox control to display text in red 10-point Verdana type:

<html> <head> <style> .Input { font: 10pt verdana; color: red; } </style> </head> <body> <form runat="server"> <asp:TextBox CssClass="Input" RunAt="server" /> </form> </body> </html>

Are ASP.NET server controls compatible with Netscape Navigator?

Most are. Some controls, such as Label, emit simple HTML tags that are compatible with virtually all browsers. Others, such as Calendar, emit a mix of HTML and client-side JavaScript. Fortunately, that JavaScript is simple enough to work with any browser that supports client-side scripting. The exception is the validation controls, which emit complex JavaScript that integrates intimately with the browser's DHTML Document Object Model (DOM). Because the DOMs used by Navigator and IE are so different, the ASP.NET validation controls don't work with Navigator. They can still validate input on the server, but they don't even attempt to validate on the client in Navigator. What namespaces are imported by default in ASPX files?

The following namespaces are imported by default. Other namespaces must be imported manually using @ Import directives.

• System • System.Collections • System.Collections.Specialized • System.Configuration • System.Text • System.Text.RegularExpressions • System.Web • System.Web.Caching • System.Web.Security • System.Web.SessionState • System.Web.UI • System.Web.UI.HtmlControls

Page 30: Net Framework Faq

• System.Web.UI.WebControls

What assemblies can I reference in an ASPX file without using @ Assembly directives?

ASP.NET links to the following assemblies by default:

• Mscorlib.dll • System.dll • System.Data.dll • System.Drawing.dll • System.Web.dll • System.Web.Services.dll • System.Xml.dll

This list of "default" assemblies is defined in the <assemblies> section of Machine.config. You can modify it by editing Machine.config or including an section in a local Web.config file. How does setting a Web control's AutoPostBack property to true cause a page to post back to the server?

With a sprinkle of JavaScript and a dash of Dynamic HTML (DHTML). Enter this into a Web form:

<asp:TextBox ID="UserName" AutoPostBack="true" RunAt="server" />

And the control returns this:

<input name="UserName" type="text" id="UserName" onchange="__doPostBack('UserName','')" language="javascript" /> . . . <script language="javascript"> <!-- function __doPostBack(eventTarget, eventArgument) { var theform = document.ctrl0; . . . theform.submit(); } // --> </script>

The <input> tag includes an onchange attribute that activates a JavaScript function named __doPostBack on the client when the control loses the input focus following a text change. __doPostBack programmatically posts the page back to the server by calling the Submit method of the DHTML object that represents the form (theform). I sometimes see ASP.NET apps that include ASHX files. What are ASHX files?

ASHX files contain HTTP handlers-software modules that handle raw HTTP requests received by ASP.NET. The following code institutes a simple HTTP handler:

<%@ WebHandler Language="C#" Class="Hello"%> using System.Web; public class Hello : IHttpHandler { public void ProcessRequest (HttpContext context)

Page 31: Net Framework Faq

{ string name = context.Request["Name"]; context.Response.Write ("Hello, " + name); } public bool IsReusable { get { return true; } } }

If this code is placed in an ASHX file named Hello.ashx and requested using the URL http://.../hello.ashx?Name=Jeff,it returns "Hello, Jeff" in the HTTP response. ASHX files provide developers with a convenient way to deploy HTTP handlers without customizing CONFIG files or modifying the IIS metabase. Can I create ASP.NET server controls of my own?

Yes. You can modify existing server controls by deriving from the corresponding control classes or create server controls from scratch by deriving from System.Web.UI.Control. Although a full treatment of custom controls is beyond the scope of this FAQ, here's a simple custom control that writes "Hello, world" to a Web page:

using System; using System.Web; using System.Web.UI; namespace Wintellect { public class HelloControl : Control { protected override void Render (HtmlTextWriter writer) { writer.Write ("Hello, World!"); } } }

A custom control emits HTML by overriding the virtual Render method it inherits from Control and using the provided HtmlTextWriter to write its output. What does the System.Web.UI.Page.RegisterClientScriptBlock method do, and do I need it when I write custom ASP.NET server controls?

RegisterClientScriptBlock enables a custom control to register a block of client-side script that the control returns to a browser. Why does it exist? So the same script block doesn't get returned multiple times if the page contains multiple instances of a control that emits client-side script. Here's the source code for a custom control called AlertButton that renders itself an as <input type="submit"> tag with an onclick attribute that displays a message using a JavaScript alert:

using System; using System.Web; using System.Web.UI; using System.Text; namespace Wintellect { public class AlertButton : Control { protected string _Text; protected string _Message; public string Text { get { return _Text; } set { _Text = value; } }

Page 32: Net Framework Faq

public string Message { get { return _Message; } set { _Message = value; } } protected override void OnPreRender (EventArgs e) { Page.RegisterClientScriptBlock ( "__doAlert", "<script language=\"javascript\">\n" + "<!--\n"+ "function __doAlert (message)\n" + "{\n" + " alert (message);\n" + "}\n" + "-->\n"+ "</script>" ); } protected override void Render (HtmlTextWriter writer) { StringBuilder builder = new StringBuilder (); builder.Append ("<input type=\"submit\" value=\""); builder.Append (_Text); builder.Append ("\" onclick=\"javascript:__doAlert (\'"); builder.Append (Message); builder.Append ("\');\" />"); writer.Write (builder.ToString ()); } } }

If the control's register tag prefix is win, then the following statement declares an AlertButton control that, when clicked, displays "Hello, world" in a message box:

<win:AlertButton Text="Click Me" Message="Hello, world" RunAt="server" />

The control uses RegisterClientScriptBlock to register the client-side script block that it returns. That script block contains the __doAlert function referenced by the <input> tag's onclick attribute. It's returned only once no matter AlertButtons a page contains. RegisterClientScriptBlock should always be called from the control's OnPreRender method so ASP.NET can control the script's position in the output. What's the difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript? RegisterClientScriptBlock is for returning blocks of client-side script containing functions. RegisterStartupScript is for returning blocks of client-script not packaged in functions-in other words, code that's to execute when the page is loaded. The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs. Can a calendar control be customized so that it limits users to selecting certain days of the week, and only dates that fall on or after today's date?

Yes. The secret is to customize the control by processing DayRender events, which are fired as the calendar renders each and every cell. Here's an example that limits selections to future Fridays and Saturdays:

<asp:Calendar OnDayRender="OnDayRender" RunAt="server" /> . . . void OnDayRender (Object sender, DayRenderEventArgs e) {

Page 33: Net Framework Faq

e.Day.IsSelectable = (e.Day.Date.DayOfWeek == DayOfWeek.Friday || e.Day.Date.DayOfWeek == DayOfWeek.Saturday) && e.Day.Date >= DateTime.Now; }

The DayRenderEventArgs passed to a DayRender event handler has a property named Day that identifies the day being rendered. This example sets Day's IsSelectable property to true or false depending on whether the day currently being rendered represents a legitimate selection. Setting IsSelectable to false prevents the control from placing a hyperlink in the corresponding cell, effectively making that cell unselectable. Is it necessary to lock application state before accessing it?

Only if you're performing a multistep update and want the update to be treated as an atomic operation. Here's an example:

Application.Lock (); Application["ItemsSold"] = (int) Application["ItemsSold"] + 1; Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1; Application.UnLock ();

By locking application state before updating it and unlocking it afterwards, you ensure that another request being processed on another thread doesn't read application state at exactly the wrong time and see an inconsistent view of it. The ASP.NET application cache doesn't have Lock and UnLock methods as application state does. Does this mean I never need to lock it?

No. It means you have to come up with your own mechanism for locking. System.Threading.ReaderWriterLock is the perfect tool for the job. Assuming rwlock is an instance of ReaderWriterLock, here's how you'd lock the application cache during an update:

rwlock.AcquireWriterLock (Timeout.Infinite); Cache["ItemsSold"] = (int) Cache ["ItemsSold"] + 1; Cache["ItemsLeft"] = (int) Cache ["ItemsLeft"] - 1; rwlock.ReleaseWriterLock ();

And here's how you'd read "ItemsSold" and "ItemsLeft" values from the cache:

rwlock.AcquireReaderLock (Timeout.Infinite); int sold = (int) Cache["ItemsSold"]; int left = (int) Cache ["ItemsLeft"]; rwlock.ReleaseReaderLock ();

As with application state, locking the application cache is only necessary when performing multistep updates that are to be treated as atomic operations. If I update session state, should I lock it, too? Are concurrent accesses by multiple requests executing on multiple threads a concern with session state?

Concurrent accesses aren't an issue with session state, for two reasons. One, it's unlikely that two requests from the same user will overlap. Two, if they do overlap, ASP.NET locks down session state during request processing so that two threads can't touch it at once. Session state is locked down when the HttpApplication instance that's processing the request fires an AcquireRequestState event and unlocked when it fires a ReleaseRequestState event. ASP.NET's application cache supports expiration policies and cache removal callbacks. Expiration policies are based on time dependencies and file dependencies. Are database dependencies supported, too? In other words, can I have an item automatically removed from the cache in response to a database update? In ASP.NET version 1, no. In version 2--well, just wait (hint, hint). Do ASP.NET forms authentication cookies provide any protection against replay attacks? Do they, for

Page 34: Net Framework Faq

example, include the client's IP address or anything else that would distinguish the real client from an attacker?

No. If an authentication cookie is stolen, it can be used by an attacker. It's up to you to prevent this from happening by using an encrypted communications channel (HTTPS). Authentication cookies issued as session cookies, do, however, include a time-out valid that limits their lifetime. So a stolen session cookie can only be used in replay attacks as long as the ticket inside the cookie is valid. The default time-out interval is 30 minutes. You can change that by modifying the timeout attribute accompanying the <forms> element in Machine.config or a local Web.config file. Persistent authentication cookies do not time-out and therefore are a more serious security threat if stolen. By default, a persistent forms authentication cookie issued by ASP.NET is valid for 50 years. Is it possible to shorten that?

Yes. Unfortunately, there is no configuration setting you can tweak to customize the lifetime of a persistent authentication cookie, but you can customize it programmatically. Here's a snippet of code that returns a persistent authentication cookie from a forms login page and limits the cookie's lifetime to 7 days:

string url = FormsAuthentication.GetRedirectUrl ("Elmo", true); FormsAuthentication.SetAuthCookie ("Elmo", true); HttpCookie cookie = Response.Cookies[FormsAuthentication.FormsCookieName]; cookie.Expires = DateTime.Now + new TimeSpan (7, 0, 0, 0); Response.Redirect (url);

To set the cookie's lifetime to something other than 7 days, simply modify the TimeSpan value. I wrote an HTTP handler and registered it in the <httpHandlers> section of a local Web.config file, but the handler never gets called. What could be wrong?

In addition to being mapped to a file type (or specific file name) in a CONFIG file, an HTTP handler has to be registered in the IIS metabase. For example, if you register an HTTP handler with the Web.config file shown below, you also have to map *.igen to Aspnet_isapi.dll in the IIS metabase. Otherwise, ASP.NET doesn't see the request and can't forward it to the handler.

<configuration> <system.web> <httpHandlers> <add verb="*" path="*.igen" type="ImageGen, ImageGenLib" /> </httpHandlers> </system.web> </configuration>

How do I send e-mail from an ASP.NET application?

MailMessage message = new MailMessage (); message.From = "[email protected]"; message.To = "[email protected]"; message.Subject = "Scheduled Power Outage"; message.Body = "Our servers will be down tonight."; SmtpMail.SmtpServer = "localhost"; SmtpMail.Send (message);

MailMessage and SmtpMail are classes defined in the .NET Framework Class Library's System.Web.Mail namespace. Due to a security change made to ASP.NET just before it shipped, you need to set SmtpMail's SmtpServer property to "localhost" even though "localhost" is the default. In addition, you must use the IIS configuration applet to enable localhost (127.0.0.1) to relay messages through the local SMTP service. How do I read an image from a database using ADO.NET and display it in a Web page?

The following ASPX file reads and displays an image from the Pubs database that comes with Microsoft SQL Server.

<%@ Import Namespace="System.Data.SqlClient" %> <%@ Import Namespace="System.Drawing" %> <%@ Import Namespace="System.Drawing.Imaging" %> <%@ Import Namespace="System.IO" %> <html>

Page 35: Net Framework Faq

<body> </body> <html> <script language="C#" runat="server"> void Page_Load(object sender, System.EventArgs e) { MemoryStream stream = new MemoryStream (); SqlConnection connection = new SqlConnection ("server=localhost;database=pubs;uid=sa;pwd="); try { connection.Open (); SqlCommand command = new SqlCommand ("select logo from pub_info where pub_id='0736'", connection); byte[] image = (byte[]) command.ExecuteScalar (); stream.Write (image, 0, image.Length); Bitmap bitmap = new Bitmap (stream); Response.ContentType = "image/gif"; bitmap.Save (Response.OutputStream, ImageFormat.Gif); } finally { connection.Close (); stream.Close (); } } </script>

Some Web service classes derive from System.Web.WebServices; others do not. What's the deal?

WebService contributes properties named Application, Session, Context, Server, and User to derived classes enabling Web services to access the ASP.NET objects of the same name. If you don't use these objects in your Web service-for example, if you don't use application state or session state-then you don't have to derive from WebService, either. Incidentally, if you want to use ASP.NET session state in a Web method, use the following WebMethod attribute to enable session state for that method:

[WebMethod (EnableSession="true")] What are VSDISCO files?

VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following VSDISCO file in a directory on your Web server, for example, it returns references to all ASMX and DISCO files in the host directory and any subdirectories not noted in <exclude> elements:

<?xml version="1.0" ?> <dynamicDiscovery xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17"> <exclude path="_vti_cnf" /> <exclude path="_vti_pvt" /> <exclude path="_vti_log" /> <exclude path="_vti_script" /> <exclude path="_vti_txt" /> </dynamicDiscovery>

How does dynamic discovery work? ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the host directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client who requests a VSDISCO file gets back what appears to be a static DISCO document.Note that VSDISCO files are disabled in the release version of ASP.NET. You can reenable them by uncommenting the line in the <httpHandlers> section of Machine.config that maps *.vsdisco to System.Web.Services.Discovery.DiscoveryRequestHandler and granting the ASPNET user account permission to read the IIS metabase. However, Microsoft is actively discouraging the use of VSDISCO files because they could represent a threat to Web server security. How does a Web service client call Web methods asynchronously?

Web service proxy classes generated by Wsdl.exe contain asynchronous as well as synchronous versions of the Web

Page 36: Net Framework Faq

service's methods. Suppose a Web service implements the following Add method:

[WebMethod] public int Add (int a, int b) { return a + b; }

A proxy generated by Wsdl.exe has BeginAdd and EndAdd methods for calling Add asynchronously. Assuming calc is an instance of the proxy class, here's how a client calls Add asynchronously:

// Initiate an async call IAsyncResult res = calc.BeginAdd (2, 2, null, null); . . . // Get the results int sum = calc.EndAdd (res);

If the call hasn't completed when EndAdd is called, EndAdd blocks until it does. If desired, a client can ask to be notified when an asynchronous call returns by providing a reference to an AsyncCallback delegate wrapping a callback method. In the next example, EndAdd won't block because it isn't called until the client is certain the method call has returned:

AsyncCallback cb = new AsyncCallback (AddCompleted); IAsyncResult res = calc.BeginAdd (2, 2, cb, null); . . . public void AddCompleted (IAsyncResult res) { int sum = calc.EndAdd (res); }

Another option is to use the IsCompleted property of the IAsyncResult interface returned by BeginAdd to determine whether the call has completed and avoid calling EndAdd until it does:

IAsyncResult res = calc.BeginAdd (2, 2, null, null); . . . if (res.IsCompleted) { int sum = calc.EndAdd (res); } else { // Try again later }

I wrote code that uses the SmtpMail and MailMessage classes to send e-mail from an ASP.NET application. The code worked fine in beta 2, but it throws an exception in the release version of ASP.NET. What's wrong?

Please see FAQ "How do I send e-mail from an ASP.NET application?" How do I upload files to Web pages in ASP.NET?

=se the HtmlInputFile class, which you can declare an instance of with an <input type="file" runat="server"/> tag. The following example is a complete ASPX file that lets a user upload an image file and a comment descibing the image. The OnUpload method writes the image and the comment to a table named Pictures in a SQL Server database

Page 37: Net Framework Faq

named MyPictures.

<%@ Import Namespace="System.Data.SqlClient" %> <form enctype="multipart/form-data" runat="server"> <table> <tr> <td>File name</td> <td><input type="file" id="Upload" runat="server" /></td> </tr> <tr> <td>Comment</td> <td><asp:TextBox ID="Comment" RunAt="server" /></td> </tr> <tr> <td></td> <td><asp:Button Text="Upload" OnClick="OnUpload" RunAt="server" /></td> </tr> </table> </form> <script language="C#" runat="server"> void OnUpload (Object sender, EventArgs e) { // Create a byte[] from the input file int len = Upload.PostedFile.ContentLength; byte[] pic = new byte[len]; Upload.PostedFile.InputStream.Read (pic, 0, len); // Insert the image and comment into the database SqlConnection connection = new SqlConnection ("server=localhost;database=mypictures;uid=sa;pwd="); try { connection.Open (); SqlCommand cmd = new SqlCommand ("insert into Pictures " + "(Picture, Comment) values (@pic, @text)", connection); cmd.Parameters.Add ("@pic", pic); cmd.Parameters.Add ("@text", Comment.Text); cmd.ExecuteNonQuery (); } finally { connection.Close (); } } </script>

How do I create an ASPX page that periodically refreshes itself?

Most browsers recognize the following META tag as a signal to automatically refresh the page every nn seconds:

<meta http-equiv="Refresh" content="nn">

Here's an ASPX file that displays the current time of day. Once displayed, it automatically refreshes every 5 seconds:

<%@ Page Language="C#" %> <meta http-equiv="Refresh" content="5"> <html> <body> <% Response.Write (DateTime.Now.ToLongTimeString ()); %>

Page 38: Net Framework Faq

</body> </html>

How can an ASP.NET application determine whether cookies are enabled in a browser?

tra cookie in an HTTP response and redirect to a page that checks for the

cookie. Here's a page that does just that:

Determining whether cookies are enabled requires a round trip to the browser and back. If you can live with an exround trip, the basic strategy is to return a

<html> <body> <form runat="server"> <asp:Button Text="Test Cookie Support" OnClick="OnTest" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void OnTest (Object sender, EventArgs e) { HttpCookie cookie = new HttpCookie ("Foo", "Bar"); Response.Cookies.Add (cookie); Response.Redirect ("OtherPage.aspx"); } </script>

And here's the page that it redirects to (OtherPage.aspx). This page uses the presence or absence of the cookie to determine whether cookies are enabled and displays the result:

<%@ Page Language="C#" %> <html> <body> <% HttpCookie cookie = Request.Cookies["Foo"]; if (cookie != null && cookie.Value == "Bar") Response.Write ("Cookies are enabled"); else Response.Write ("Cookies are not enabled"); %> </body> </html>

Is it possible to prevent a browser from caching an ASPX page?

tore on the HttpCachePolicy object exposed through the Response object's Cache property, as demonstrated here: You bet. Just call SetNoS

<%@ Page Language="C#" %> <html> <body> <% Response.Cache.SetNoStore (); Response.Write (DateTime.Now.ToLongTimeString ()); %> </body> </html>

SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP response. In this example, it

ns and pop up a message box asking the user for prevents caching of a Web page that shows the current time. How do I create a DataGrid with Delete butto

Page 39: Net Framework Faq

confirmation before deleting a record?

f

eted

That k to the server (thus preventing

OnDeleteRecord from being called) if the user clicks Cancel rather than OK.

The ASPX file below demonstrates the proper technique. It populates a DataGrid with content from the Titles table othe Pubs database that comes with Microsoft SQL Server. The DataGrid's leftmost column contains a row of Delete buttons. The OnDeleteRecord method simulates a record deletion by writing the Title field of the record to be delto a Label control. The OnAttachScript method, which is called once for each row in the DataGrid in response to ItemCreated events, attaches to each button an OnClick attribute that activates a bit of client-side JavaScript.script displays a confirmation dialog and prevents the page from posting bac

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <body> <form runat="server"> <asp:DataGrid ID="MyDataGrid" AutoGenerateColumns="false" CellPadding="2" BorderWidth="1" BorderColor="lightgray" Font-Name="Verdana" Font-Size="8pt" GridLines="vertical" Width="90%" OnItemCreated="OnAttachScript" OnItemCommand="OnDeleteRecord" RunAt="server"> <Columns> <asp:ButtonColumn Text="Delete" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center" ButtonType="PushButton" CommandName="Delete" /> <asp:BoundColumn HeaderText="Item ID" DataField="title_id" /> <asp:BoundColumn HeaderText="Title" DataField="title" /> <asp:BoundColumn HeaderText="Price" DataField="price" DataFormatString="{0:c}" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="right" /> </Columns> <HeaderStyle BackColor="teal" ForeColor="white" Font-Bold="true" /> <ItemStyle BackColor="white" ForeColor="darkblue" /> <AlternatingItemStyle BackColor="beige" ForeColor="darkblue" /> </asp:DataGrid> <asp:Label ID="Output" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { SqlDataAdapter adapter = new SqlDataAdapter ("select * from titles where price != 0", "server=localhost;database=pubs;uid=sa;pwd="); DataSet ds = new DataSet (); adapter.Fill (ds); MyDataGrid.DataSource = ds; MyDataGrid.DataBind (); } } void OnAttachScript (Object sender, DataGridItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item ||

Page 40: Net Framework Faq

e.Item.ItemType == ListItemType.AlternatingItem) { WebControl button = (WebControl) e.Item.Cells[0].Controls[0]; button.Attributes.Add ("onclick", "return confirm (\"Are you sure?\");"); } } void OnDeleteRecord (Object sender, DataGridCommandEventArgs e) { if (e.CommandName == "Delete") { Output.Text = "Deleted \"" + e.Item.Cells[2].Text + "\""; } } </script>

How do I localize an ASP.NET application so that it formats dates and times based on the requestor's locale?

Deploy the following Global.asax file in the application's virtual root:

<%@ Import Namespace="System.Threading" %> <%@ Import Namespace="System.Globalization" %> <script language="C#" runat="server"> void Application_BeginRequest (Object sender, EventArgs e) { try { if (Request.UserLanguages.Length > 0) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture (Request.UserLanguages[0]); } } catch (ArgumentException) { // Do nothing if CreateSpecificCulture fails } } </script>

Application_BeginRequest executes at the beginning of each and every request. This example reads the requestor's preferred language from the Request object's UserLanguage property (which is populated with information found inthe request's Accept-Language header), creates a CultureInfo object from it, and assigns the CultureInfo object to the CurrentCulture property of the thread that's processing the request. FCL methods that are cultu

re-aware (such as DateTime.ToShortDateString) will format dates, times, currency values, and numbers accordingly. What does AspCompat="true" mean and when should I use it?

access intrinsic ASP objects such as Request and Response. The following directive sets AspCompat to true:

AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but should be set to true in any ASPX file that creates apartment-threaded COM objects--that is, COM objects registered ThreadingModel=Apartment. That includes all COM objects written with Visual Basic 6.0. AspCompat should also be set to true (regardless of threading model) if the page creates COM objects that

<%@ Page AspCompat="true" %>

Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available to the COM components byplacing unmanaged wrappers around the equivalent ASP.NET objects. Second, it improves the performance of that the page places to apartment-threaded COM objects by ensuring that the page (actually, the thread that processes the request for the page) and the COM objects it creates share an apartment. AspCompat="true" forcASP.NET request threads into single-threaded apartments (STAs). If those threads create COM objects marked ThreadingModel=Apartment, then the objects are created in the same STAs as the threads that created them. Without AspCompat="true," request threads run in a multithreaded apartment (MTA) and each call to an STA-based COM object incurs a performance hit when it's marshaled across apartment boundaries.Do not set AspCompat tif your page uses no COM objects or if it uses COM objects that don'

calls

es

o true t access ASP intrinsic objects and that are

registered ThreadingModel=Free or ThreadingModel=Both.

Page 41: Net Framework Faq

I've developed a custom Windows Forms control that I'd like to use in a Web Form. I've heard that ASP.NET can use Windows Forms controls. Is that true? If so, how do I create a Windows Forms control in a Web Form?

onstrate, here's the source code for a very simple slider control-one that derives from the FCL's TrackBar class:

You can embed Windows Forms controls in Web pages using <object> tags similar to those that declare ActiveX controls. To dem

namespace Wintellect { public class WebSlider : System.Windows.Forms.TrackBar {} }

Compile this source code into a DLL with the following command (assuming the source code file is named Controls.cs):

csc /t:library controls.cs

Copy the resulting DLL (Controls.dll) to the virtual directory of your choice on your Web server. Now create a text file named Slider.aspx in the same directory and add the following HTML:

<html> <body> <form> <object id="Slider" classid="http:Controls.dll#Wintellect.WebSlider" width="64" height="256"> <param name="Minimum" value="0"> <param name="Maximum" value="10"> <param name="Value" value="3"> <param name="Orientation" value="Vertical"> <param name="BackColor" value="gainsboro"> </object> </form> </body> </html>

The <object> tag declares an instance of the control and names it Slider. It also uses <param> tags to initialize some of the control's properties. Open the ASPX file in your browser and the slider control should be displayed. IE downloads the control implementation from the Web server, so you don't have to install Controls.dll on the client. The client must, however, have the .NET Framework installed. Internet Explorer 5.01 or higher is required on the

, what must I do to allow a server-side event handler to determine the position of the slider's thumb?

extracts the value from the request. In this example, the event handler writes the thumb position to the Web page.

client, too. If I use the slider control in the previous example in a Web page

The trick is to intercept the form submit event fired before the form posts back to the server and add the thumb position to the form's postback data. Here's a modified version of the ASPX file in the previous example that does justthat. The onsubmit attribute in the <form> tag calls the JavaScript function SubmitForm before the form posts back to the server. SubmitForm writes the slider's thumb position to a hidden <input> control named __THUMBPOS. The browser submits the __THUMBPOS control's value to the server, and the server-side event handler

<html> <body> <form id="MyForm" onsubmit="javascript:return SubmitForm ();" runat="server"> <input type="hidden" name="__THUMBPOS" value="" > <object id="Slider" classid="http:Controls.dll#Wintellect.WebSlider" width="64" height="256">

Page 42: Net Framework Faq

<param name="Minimum" value="0"> <param name="Maximum" value="10"> <param name="Value" value="3"> <param name="Orientation" value="Vertical"> <param name="BackColor" value="gainsboro"> </object> <br><br> <input type="submit" value="Test" onserverclick="ShowThumbPos" runat="server"> <br><br> <span id="Output" runat="server" /> </form> </body> </html> <script language="JavaScript"> function SubmitForm () { MyForm.__THUMBPOS.value = MyForm.Slider.value; return true; } </script> <script language="C#" runat="server"> void ShowThumbPos (Object sender, EventArgs e) { Output.InnerText = "You chose " + Request["__THUMBPOS"]; } </script>

If I use the slider control in the previous example in a Web page, the slider's thumb snaps back to its default position each time the page posts back to the server. Is there a way to make the thumb stay put?

to

S value submitted in the request if the page is being returned following a postback. It's not pretty, but it works.

The ASPX file below shows one way to do it. The <param> tag that controls the slider's thumb position is no longer embedded in the page's HTML; instead, it's output programmatically with Response.Write. That enables the page emit a <param> tag containing a default value if the page is fetched outside of a postback, or a <param> tag containing the __THUMBPO

<%@ Page Language="C#" %> <html> <body> <form id="MyForm" onsubmit="javascript:return SubmitForm ();" runat="server"> <input type="hidden" name="__THUMBPOS" value=""> <object id="Slider" classid="http:Controls.dll#Wintellect.WebSlider" width="64" height="256"> <param name="Minimum" value="0"> <param name="Maximum" value="10"> <% if (Request["__THUMBPOS"] == null) Response.Write ("<param name=\"Value\" value=\"3\">\r\n"); else Response.Write ("<param name=\"Value\" value=\"" + Request["__THUMBPOS"] + "\">\r\n"); %> <param name="Orientation" value="Vertical"> <param name="BackColor" value="gainsboro"> </object> <br><br> <input type="submit" value="Test" onserverclick="ShowThumbPos" runat="server"> <br><br> <span id="Output" runat="server" /> </form>

Page 43: Net Framework Faq

</body> </html> <script language="JavaScript"> function SubmitForm () { MyForm.__THUMBPOS.value = MyForm.Slider.value; return true; } </script> <script language="C#" runat="server"> void ShowThumbPos (Object sender, EventArgs e) { Output.InnerText = "You chose " + Request["__THUMBPOS"]; } </script>

How can I create a DataGrid that displays a column of images obtained from a database?

The following ASPX file demonstrates how:

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <body> <form runat="server"> <asp:DataGrid ID="MyDataGrid" RunAt="server" AutoGenerateColumns="false" CellPadding="2" BorderWidth="1" BorderColor="lightgray" Font-Name="Verdana" Font-Size="8pt" GridLines="vertical" Width="100%"> <Columns> <asp:TemplateColumn HeaderText="Photo" HeaderStyle-HorizontalAlign="center"> <ItemTemplate> <center> <img src='<%# "NorthwindImageGrabber.ashx?id=" + DataBinder.Eval (Container.DataItem, "EmployeeID") %>'> </center> </ItemTemplate> </asp:TemplateColumn> <asp:BoundColumn HeaderText="Last Name" HeaderStyle-HorizontalAlign="center" DataField="LastName" /> <asp:BoundColumn HeaderText="First Name" HeaderStyle-HorizontalAlign="center" DataField="FirstName" /> <asp:BoundColumn HeaderText="Title" HeaderStyle-HorizontalAlign="center" DataField="Title" /> </Columns> <HeaderStyle BackColor="teal" ForeColor="white" Font-Bold="true" /> <ItemStyle BackColor="white" ForeColor="darkblue" /> <AlternatingItemStyle BackColor="beige" ForeColor="darkblue" /> </asp:DataGrid> </form> </body> </html> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) {

Page 44: Net Framework Faq

SqlConnection connection = new SqlConnection ("server=localhost;database=northwind;uid=sa;pwd="); try { connection.Open (); SqlCommand command = new SqlCommand ("select employeeid, lastname, firstname, title from employees", connection); SqlDataReader reader = command.ExecuteReader (); MyDataGrid.DataSource = reader; MyDataGrid.DataBind (); } finally { connection.Close (); } } } </script>

This ASPX file contains a DataGrid that displays data from the Employees table of SQL Server's Northwind daEach row rendered by the DataGrid represents one employee, and each row's leftmost column contains the employee's picture. The picture comes from the table's Photo field. The image is rendered btag, which emits an <img> tag accompanied by a src attribute that points to a file named NorthwindImageGrabber.ashx. Inside the ASHX file is an HTTP handler that retrieves an image from the database. A query string a

tabase.

y the <ItemTemplate>

ppended to the URL tells the handler which image to retrieve. Here's NorthwindImageGrabber.ashx's source code:

<%@ WebHandler Language="C#" Class="ImageGrabber" %> using System; using System.Web; using System.Drawing; using System.Drawing.Imaging; using System.Data.SqlClient; using System.IO; public class ImageGrabber : IHttpHandler { public void ProcessRequest (HttpContext context) { string id = (string) context.Request["id"]; if (id != null) { MemoryStream stream = new MemoryStream (); SqlConnection connection = new SqlConnection ("server=localhost;database=northwind;uid=sa;pwd="); Bitmap bitmap = null; Image image = null; try { connection.Open (); SqlCommand cmd = new SqlCommand ("select photo from employees where employeeid='" + id + "'", connection); byte[] blob = (byte[]) cmd.ExecuteScalar (); stream.Write (blob, 78, blob.Length - 78); bitmap = new Bitmap (stream); // Shrink the image, but maintain its aspect ratio int width = 48; int height = (int) (width * ((double) bitmap.Height / (double) bitmap.Width)); image = bitmap.GetThumbnailImage (width, height, null, IntPtr.Zero);

Page 45: Net Framework Faq

context.Response.ContentType = "image/jpeg"; image.Save (context.Response.OutputStream, ImageFormat.Jpeg); } finally { if (image != null) image.Dispose (); if (bitmap != null) bitmap.Dispose (); stream.Close (); connection.Close (); } } } public bool IsReusable { get { return true; } } }

The ProcessRequest method, which is called every time the ASHX file is requested, retrieves the image from the database and returns it to the client as a JPEG. For good measure, it also shrinks the image down to thumbnail size using Image.GetThumbnailImage. NorthwindImageGrabber.ashx discards the first 78 bytes of each image becathe Northwind database's Photo

use field doesn't store raw images; it stores BMP bitmaps prefixed by 78 bytes of

t works like an ISAPI filter-that is, that sees requests and responses and perhaps modifies them, too?

g it in Web.config. Here's a simple HTTP module written in C# that appends "Hello, world" to every response:

unrelated header information. Is it possible to write an ASP.NET handler tha

You can do it by writing an HTTP module-a class that implements IHttpModule-and registerin

using System; using System.Web; public class MyModule : IHttpModule { public void Init (HttpApplication application) { application.EndRequest += new EventHandler (Application_EndRequest); } void Application_EndRequest (Object source, EventArgs e) { HttpApplication application = (HttpApplication) source; HttpContext context = application.Context; context.Response.Write ("Hello, world"); } public void Dispose () { } }

Here's how you register it if MyModule is in an assembly named CustomModules:

<configuration> <system.web> <httpModules> <add name="MyModule" type="MyModule, CustomModules" /> </httpModules> </system.web> </configuration>

Page 46: Net Framework Faq

An HTTP module can handle the per-request events fired by HttpApplication instances, and it can fire events of its own that can be processed in Global.asax. To deploy the module, simply drop the DLL containing MyModule into the

How can ASP.NET apps transmit data from one page to another?

age named PageOne.aspx that encodes a string typed by the user in a query string and passes it to PageTwo.aspx:

application root's bin subdirectory.

One way to transfer data from page to page is to have the sending page encode the data in a query string and the receiving page read the data from the request. Here's the source code for a p

<!-- PageOne.aspx --> <html> <body> <form runat="server"> <asp:TextBox ID="Input" RunAt="server" /> <asp:Button Text="NextPage" OnClick="OnNextPage" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void OnNextPage (Object sender, EventArgs e) { Response.Redirect ("PageTwo.aspx?Input=" + Input.Text); } </script>

And here's the page it redirects to, which echoes what the user typed:

<!-- PageTwo.aspx --> <%@ Page Language="C#" %> <html> <body> <% Response.Write ("You typed \"" + Request["Input"] + "\""); %> </body> </html>

Another way to pass data from one page to another--a technique that has the added benefit of keeping the data on the server and not exposing it to the user--is to pass the data in session state, as demonstrated here:

<!-- PageOne.aspx --> <html> <body> <form runat="server"> <asp:TextBox ID="Input" RunAt="server" /> <asp:Button Text="NextPage" OnClick="OnNextPage" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void OnNextPage (Object sender, EventArgs e) { Session["Input"] = Input.Text; Response.Redirect ("PageTwo.aspx"); } </script>

<!-- PageTwo.aspx --> <%@ Page Language="C#" %>

Page 47: Net Framework Faq

<html> <body> <% Response.Write ("You typed \"" + Session["Input"] + "\""); %> </body> </html>

If you use Server.Transfer rather than Response.Redirect to transfer control to another page, you can use public fields in the sending page's code-behind class to transmit data. The following example demonstrates how:

<!-- PageOne.aspx --> <%@ Page Inherits="PageOneClass" %> <html> <body> <form runat="server"> <asp:TextBox ID="Input" RunAt="server" /> <asp:Button Text="NextPage" OnClick="OnNextPage" RunAt="server" /> </form> </body> </html>

// PageOneClass.cs using System; using System.Web.UI; using System.Web.UI.WebControls; public class PageOneClass : Page { public string _Input; protected TextBox Input; public void OnNextPage (Object sender, EventArgs e) { _Input = Input.Text; Server.Transfer ("PageTwo.aspx"); } }

<!-- PageTwo.aspx --> <%@ Page Language="C#" %> <html> <body> <% PageOneClass prevpage = (PageOneClass) Context.Handler; Response.Write ("You typed \"" + prevpage._Input + "\""); %> </body> </html>

How do I display an ASPX or HTML page in a new browser window in ASP.NET?

The following tag creates a hyperlink that, when clicked, opens an ASPX file in a new window:

<asp:HyperLink Text="Wintellect home page" NavigateUrl="http://www.wintellect.com/default.aspx" Target="_new" RunAt="server" />

How do I initialize a TextBox whose TextMode is "password" with a password? Initializing the TextBox's Text property doesn't seem to work.

This won't work:

Page 48: Net Framework Faq

<asp:TextBox Text="imbatman" TextMode="Password" ID="Password" RunAt="server" />

But this will:

<asp:TextBox TextMode="Password" ID="Password" RunAt="server" /> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { Password.Attributes.Add ("value", "imbatman"); } </script>

The latter code fragment manually adds a value="imbatman" attribute to the <input> tag output by the TextBox control, causing the specified text to appear in the TextBox.You can also initialize a password TextBox by including a Value attribute in the control tag, as demonstrated below:

<asp:TextBox Value="imbatman" TextMode="Password" ID="Password" RunAt="server" />

I know I can write custom server controls by deriving from Control or WebControl. But can I modify the behavior of existing controls by deriving from them and modifying their output?

to

r

's Text property and implements a set accessor that throws an exception if a non-numeric string is written to it.

You bet. Here's a custom control named NumTextBox that derives from TextBox and adds an onkeydown attribute the <input> tag that TextBox outputs. That attribute references a local JavaScript function that filters out non-numeric keys, producing a TextBox that accepts only numbers. For good measure, NumTextBox senses the browsetype and renders differently to Internet Explorer and Netscape Navigator, enabling it to work in either browser. It also overrides TextBox

using System; using System.Web.UI; using System.Web.UI.WebControls; namespace Wintellect { public class NumTextBox : TextBox { string IEClientScriptBlock = "<script language=\"javascript\">\n" + "<!--\n" + "var keys = new Array (8, 9, 13, 33, 34, 35, " + "36, 37, 39, 45, 46);\n" + "function isKeyValid (keyCode)\n" + "{\n" + " return ((keyCode >= 48 && keyCode <= 57) || " + "isAuxKey (keyCode));\n" + "}\n" + "function isAuxKey (keyCode)\n" + "{\n" + " for (i=0; i<keys.length; i++)\n" + " if (keyCode == keys[i])\n" + " return true;\n" + " return false;\n" + "}\n" + "-->\n" + "</script>"; string NetscapeClientScriptBlock = "<script language=\"javascript\">\n" + "<!--\n" +

Page 49: Net Framework Faq

"function isKeyValid (keyCode)\n" + "{\n" + " return ((keyCode >= 48 && keyCode <= 57) || " + "keyCode == 8 || keyCode == 13);\n" + "}\n" + "-->\n" + "</script>"; public override string Text { get { return base.Text; } set { // Make sure value is numeric before storing it Convert.ToInt64 (value); base.Text = value; } } protected override void OnPreRender (EventArgs e) { string browser = Context.Request.Browser.Type.ToUpper (); int version = Context.Request.Browser.MajorVersion; if (browser.IndexOf ("IE") > -1 && version >= 4) Page.RegisterClientScriptBlock ("NumTextBoxScript", IEClientScriptBlock); else if (browser.IndexOf ("NETSCAPE") > -1 && version >= 4) Page.RegisterClientScriptBlock ("NumTextBoxScript", NetscapeClientScriptBlock); } protected override void Render (HtmlTextWriter writer) { string browser = Context.Request.Browser.Type.ToUpper (); int version = Context.Request.Browser.MajorVersion; if (browser.IndexOf ("IE") > -1 && version >= 4) writer.AddAttribute ("onkeydown", "javascript:return isKeyValid (window.event.keyCode)"); else if (browser.IndexOf ("NETSCAPE") > -1 && version >= 4) writer.AddAttribute ("onkeydown", "javascript:return isKeyValid (event.which)"); base.Render (writer); } } }

Here's an ASPX file you can use to test the control. It assumes that the control is compiled into an assembly named NumTextBoxControl.

<%@ Register TagPrefix="win" Namespace="Wintellect" Assembly="NumTextBoxControl" %> <html> <body> <form runat="server"> <win:NumTextBox runat="server" /> </form> </body> </html>

Is it possible to associate hidden values--say, values from an identity field in a database table--with items in a DataGrid?

Page 50: Net Framework Faq

You bet. Just declare a BoundColumn in the DataGrid and set its Visible property to false, like so:

<asp:BoundColumn DataField="ItemID" Visible="false" />

The column won't show up in the DataGrid, but you'll be able to read data from it following a postback just as if it were visible. How do I configure a DataGrid to show a column of row numbers: 1, 2, 3, 4, and so on?

The easiest way to do it is to use a TemplateColumn. The following ASPX file demonstrates how. The TemplateColumn displays the value of a rownum field that is incremented each time a row is output.

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <body> <form runat="server"> <asp:DataGrid ID="MyDataGrid" AutoGenerateColumns="false" RunAt="server"> <Columns> <asp:TemplateColumn HeaderText="Number" ItemStyle-HorizontalAlign="center"> <ItemTemplate> <%# rownum++ %> </ItemTemplate> </asp:TemplateColumn> <asp:BoundColumn HeaderText="Title" DataField="title" /> </Columns> <HeaderStyle HorizontalAlign="center" /> </asp:DataGrid> </form> </body> </html> <script language="C#" runat="server"> int rownum = 1; void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { SqlDataAdapter adapter = new SqlDataAdapter ( "select title from titles where price != 0", "server=localhost;database=pubs;uid=sa" ); DataSet ds = new DataSet (); adapter.Fill (ds); MyDataGrid.DataSource = ds; MyDataGrid.DataBind (); } } </script>

Is it possible to call Fill on a DataAdapter and fill two DataTables in a DataSet with a single call?

You bet. Here's a sample that demonstrates how by performing a double query and binding each of the resulting DataTables to a different DataGrid.

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <body>

Page 51: Net Framework Faq

<form runat="server"> <asp:DataGrid ID="DataGrid1" RunAt="server" /> <asp:DataGrid ID="DataGrid2" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { SqlDataAdapter adapter = new SqlDataAdapter ( "select * from titles; select * from authors", "server=localhost;database=pubs;uid=sa" ); DataSet ds = new DataSet (); adapter.Fill (ds); DataGrid1.DataSource = ds.Tables[0]; DataGrid1.DataBind (); DataGrid2.DataSource = ds.Tables[1]; DataGrid2.DataBind (); } } </script>

I'm trying to use Server.CreateObject to instantiate a legacy COM component in an ASPX page. If I use VB.NET, I can create and call the COM object just fine. But the same code written in C# doesn't compile. The compiler complains that the method I'm calling isn't a member of Object. What gives?

You've discovered an interesting feature of VB.NET--namely, that it trades type safety for simplicity when late binding to COM objects. Check out the following VB.NET code sample, which instantiates a COM object (ProgID="Wintellect.Math") and calls its Add method to add 2 and 2:

Dim Sum As Integer Dim WinMath As Object WinMath = Server.CreateObject ("Wintellect.Math") Sum = WinMath.Add (2, 2)

This code works just fine, despite that fact that Add is not a member of System.Object. The VB.NET compiler relaxes its type-checking rules to simplify your code. The C# compiler, however, does not. The following code won't compile:

Object math = Server.CreateObject ("Wintellect.Math") int sum = WinMath.Add (2, 2)

The solution for C# programmers is to late-bind to the COM object using System.Type.InvokeMember. Here's the C# equivalent of the VB.NET code above:

Type t = Type.GetTypeFromProgID ("Wintellect.Math"); Object math = Server.CreateObject (t); Object[] args = { 2, 2 }; int sum = (int) t.InvokeMember ("Add", BindingFlags.InvokeMethod, null, math, args);

It's not pretty, but it works, and it perfectly illustrates the extra effort required to accomplish late binding in C#. I'm trying to use ASP.NET's HtmlInputFile control to upload files to a Web server, but the control's PostedFile property is always null—even after I select a file and post back to the server. What am I doing wrong?

Most likely you forgot to include an enctype="multipart/form-data" attribute in your <form> tag. The following HTML

Page 52: Net Framework Faq

form doesn't support file uploads:

<form runat="server"> <input type="file" id="MyFile" runat="server" /> </form>

But the next one does. Decorate the <form> tag as shown here and file uploads will work just fine:

<form enctype="multipart/form-data" runat="server"> <input type="file" id="MyFile" runat="server" /> </form>

ASP.NET's @ OutputCache directive lets me cache different versions of a page based on varying input parameters, HTTP headers, and browser types. I'd also like to be able to cache based on varying session IDs. Is that possible?

You bet. Here's a sample page that uses a VaryByCustom attribute to cache different versions of a page based on session IDs:

<%@ Page Language="C#" %> <%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="SessionID" %> <html> <body> <% Session["MyData"] = "Foo"; // Make the session persistent Response.Write ("Your session ID is " + Session.SessionID); Response.Write ("<br>"); Response.Write ("The current time is " + DateTime.Now.ToLongTimeString ()); %> </body> </html>

In order for VaryByCustom="SessionID" to work, you must include in the application root a Global.asax file containing the following GetVaryByCustomString method:

<script language="C#" runat="server"> public override string GetVaryByCustomString (HttpContext context, string arg) { if (arg.ToLower () == "sessionid") { HttpCookie cookie = context.Request.Cookies["ASP.NET_SessionId"]; if (cookie != null) return cookie.Value; } return base.GetVaryByCustomString (context, arg); } </script>

GetVaryByCustomString is a mechanism for extending ASP.NET's page output cache. This implementation of GetVaryByCustomString, which overrides the one inherited from HttpApplication, responds to a VaryByCustom="SessionID" attribute in an @ OutputCache directive by returning the current session ID, if present. ASP.NET responds by caching different versions of the page if the session IDs differ. Note that GetVaryByCustomString extracts the session ID from the session cookie, not from the session's SessionID property. That's because the request has yet to be associated with a session when GetVaryByCustomString is called. An unpleasant side effect is that this technique doesn't work with cookieless session state. Also note that the page won't be cached until a user requests the page for the second time, because the first request lacks a valid session cookie. I've noticed that DataGrids round-trip tons of information in view state, decreasing the effective bandwidth of the connection. Is there anything I can do to reduce the DataGrid's view state usage?

Page 53: Net Framework Faq

You bet. Set the DataGrid's EnableViewState property to false, as shown here:

<asp:DataGrid RunAt="server" EnableViewState="false" ... />

Once you make this change, you'll also have to reinitialize the DataGrid in every request (even during postbacks), because the DataGrid will no longer retain its state across postbacks. In other words, instead of doing this:

void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { // TODO: Initialize the DataGrid } }

Do this:

void Page_Load (Object sender, EventArgs e) { // TODO: Initialize the DataGrid }

The performance you lose may be more than compensated for by the effective bandwidth you gain--especially if instead of querying a database on every request, you query once, cache the data, and initialize the DataGrid from the cache. Is it possible to create a DataGrid that uses scrolling rather than paging to provide access to a long list of items?

With a little help from a <div> tag, yes. The following ASPX file displays the "Products" table of SQL Server's Northwind database in a scrolling table:

<%@ Import Namespace="System.Data.SqlClient" %> <html> <body> <form runat="server"> <div style="height: 256px; overflow: auto"> <asp:DataGrid ID="MyDataGrid" Width="100%" RunAt="server" /> </div> </form> </body> </html> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { SqlConnection connection = new SqlConnection ("server=localhost;database=northwind;uid=sa"); try { connection.Open (); SqlCommand command = new SqlCommand ("select * from products", connection); SqlDataReader reader = command.ExecuteReader (); MyDataGrid.DataSource = reader; MyDataGrid.DataBind (); } finally { connection.Close (); }

Page 54: Net Framework Faq

} } </script>