Vous êtes sur la page 1sur 43

.

NET Technical FAQs


Q. 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). Q. 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. Q. 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. Q. 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. Q. What tools can I use to develop .NET applications? There are a number of tools, described here in ascending order of cost: .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 2003: 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 2003: If you have a license for Visual Studio 6.0, you can get the upgrade. You can also upgrade from VS.NET 2002 for a token $30. Visual Studio.NET includes support for all the MS languages (C#, C++, VB.NET) and has extensive wizard support.

.NET Technical FAQs


At the top end of the price spectrum are the Visual Studio.NET 2003 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. Q. 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. Q. 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. Q. 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)."
Basic terminology

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

.NET Technical FAQs


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

.NET Technical FAQs


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

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

.NET Technical FAQs


Q. 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, 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. Q. 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 subdirectories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache. Q. 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.
Application Domains

Q. 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. Q. 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;

.NET Technical FAQs


using System.Runtime.Remoting; public class CAppDomainInfo : MarshalByRefObject { public string GetAppDomainInfo() { return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName; } } 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; } } Q. 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.
Garbage Collection

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

.NET Technical FAQs


Q. 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. Q. 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 reference-counting or ownershipmanagement mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this. Q. 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. Q. 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 cleanup 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.

.NET Technical FAQs


Q. 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. Q. 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.
Serialization

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

.NET Technical FAQs


Q. 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. Q. 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. Q. 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.
Attributes

Q. 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. [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. Q. 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 { }

.NET Technical FAQs

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 ); } } Q. 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/
Code Access Security

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

10

.NET Technical FAQs


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 000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD06 F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E08 07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5C 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. Q. 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 commandline. The underlying runtime never sees it. Q. 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 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. Q. 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)

11

.NET Technical FAQs


Q. 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. Q. 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
Intermediate Language (IL)

Q. 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. Q. Can source code be reverse-engineered from IL? Yes, it is often relatively straightforward to regenerate high-level source (e.g. C#) from IL. Q. 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 reverseengineering 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. Q. 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. Q. 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.

12

.NET Technical FAQs


Q. 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: 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. Q. 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. Q. 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 Q. 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. 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 ]

13

.NET Technical FAQs


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

14

.NET Technical FAQs


Q. 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 { [ClassInterface(ClassInterfaceType.AutoDual)] 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. 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. Q. 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.

15

.NET Technical FAQs


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. 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. Q. 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 ); } } Q. 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. Q. How do I write to a text file? Similar to the read example, except use StreamWriter instead of StreamReader.

16

.NET Technical FAQs


Q. 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. Q. 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 ); } Q. 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 );

17

.NET Technical FAQs


Q. 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" ); while( reader.Read() ) { if( reader.NodeType == XmlNodeType.Element && reader.Name == "PERSON" ) { reader.Read(); // Skip to the child text Console.WriteLine( reader.Value ); } } Q. 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

18

.NET Technical FAQs


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; } 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(); Q. 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. Q. 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 }

19

.NET Technical FAQs


// DoWork is executed on a thread from the thread pool. static void DoWork( object state ) { Console.WriteLine( state ); } } Q.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. Q. 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 { 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:

20

.NET Technical FAQs


class C { public void f() { lock( m_object ) { ... } } private m_object = new object(); } Q.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. Q.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!" ); 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. Q. 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) { }

21

.NET Technical FAQs


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.

ASP.NET
What is view state and use of it? The current property settings of an ASP.NET page and those of any ASP.NET server controls contained within the page. ASP.NET can detect when a form is requested for the first time versus when the form is posted (sent to the server), which allows you to program accordingly. What are user controls and custom controls? Custom controls: A control authored by a user or a third-party software vendor that does not belong to the .NET Framework class library. This is a generic term that includes user controls. A custom server control is used in Web Forms (ASP.NET pages). A custom client control is used in Windows Forms applications. User Controls: In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used as a server control. An ASP.NET user control is authored declaratively and persisted as a text file with an .ascx extension. The ASP.NET page framework compiles a user control on the fly to a class that derives from the System.Web.UI.UserControl class. What are the validation controls? A set of server controls included with ASP.NET that test user input in HTML and Web server controls for programmer-defined requirements. Validation controls perform input checking in server code. If the user is working with a browser that supports DHTML, the validation controls can also perform validation using client script. What's the difference between Response.Write() andResponse.Output.Write()? The latter one allows you to write formattedoutput. What methods are fired during the page load? Init() When the page is instantiated, Load() - when the page is loaded into server memory,PreRender () - the brief moment before the page is displayed to the user as HTML, Unload() - when page finishes loading.

22

.NET Technical FAQs


Where does the Web page belong in the .NET Framework class hierarchy? System.Web.UI.Page Where do you store the information about the user's locale? System.Web.UI.Page.Culture What's the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"? CodeBehind is relevant to Visual Studio.NET only. What's a bubbled event? When you have a complex control, likeDataGrid, writing an event processing routine for each object (cell, button,row, etc.) is quite tedious. The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents. Suppose you want a certain ASP.NET function executed on MouseOver over a certain button. Where do you add an event handler? It's the Attributesproperty, the Add function inside that property. e.g. btnSubmit.Attributes.Add("onMouseOver","someClientCode();") What data type does the RangeValidator control support? Integer,String and Date. What are the different types of caching? Caching is a technique widely used in computing to increase performance by keeping frequently accessed or expensive data in memory. In context of web application, caching is used to retain the pages or data across HTTP requests and reuse them without the expense of recreating them.ASP.NET has 3 kinds of caching strategiesOutput CachingFragment CachingData CachingOutput Caching: Caches the dynamic output generated by a request. Some times it is useful to cache the output of a website even for a minute, which will result in a better performance. For caching the whole page the page should have OutputCache directive.<%@ OutputCache Duration="60" VaryByParam="state" %> Fragment Caching: Caches the portion of the page generated by the request. Some times it is not practical to cache the entire page, in such cases we can cache a portion of page<%@ OutputCache Duration="120" VaryByParam="CategoryID;SelectedID"%> Data Caching: Caches the objects programmatically. For data caching asp.net provides a cache object for eg: cache["States"] = dsStates; What do you mean by authentication and authorization? Authentication is the process of validating a user on the credentials (username and password) and authorization performs after authentication. After Authentication a user will be verified for performing the various tasks, It access is limited it is known as authorization.

23

.NET Technical FAQs


What are different types of directives in .NET? @Page: Defines page-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .aspx files <%@ Page AspCompat="TRUE" language="C#" %> @Control:Defines control-specific attributes used by the ASP.NET page parser and compiler. Can be included only in .ascx files. <%@ Control Language="VB" EnableViewState="false" %> @Import: Explicitly imports a namespace into a page or user control. The Import directive cannot have more than one namespace attribute. To import multiple namespaces, use multiple @Import directives. <% @ Import Namespace="System.web" %> @Implements: Indicates that the current page or user control implements the specified .NET framework interface.<%@ Implements Interface="System.Web.UI.IPostBackEventHandler" %> @Register: Associates aliases with namespaces and class names for concise notation in custom server control syntax.<%@ Register Tagprefix="Acme" Tagname="AdRotator" Src="AdRotator.ascx" %> @Assembly: Links an assembly to the current page during compilation, making all the assembly's classes and interfaces available for use on the page. <%@ Assembly Name="MyAssembly" %><%@ Assembly Src="MySource.vb" %> @OutputCache: Declaratively controls the output caching policies of an ASP.NET page or a user control contained in a page< %@ OutputCache Duration="#ofseconds" Location="Any | Client | Downstream | Server | None" Shared="True | False" VaryByControl="controlname" VaryByCustom="browser | customstring" VaryByHeader="headers" VaryByParam="parametername" %> @Reference: Declaratively indicates that another user control or page source file should be dynamically compiled and linked against the page in which this directive is declared. How do I debug an ASP.NET application that wasn't written with Visual Studio.NET and that doesn't use codebehind? 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" %> statement at the top of an ASPX file or a <COMPILATION debug="true" />statement in a Web.config file. 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. You can modify it by editing Machine.config or including an section in a local Web.config file.

24

.NET Technical FAQs


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.<%@ Reference Control="MyControl.ascx" %> 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. 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. Do ASP.NET forms authentication cookies provide any protection against replay attacks? Do they, for 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 timeout and therefore are a more serious security threat if stolen. How do I send e-mail from an ASP.NET application? MailMessage message = new MailMessage (); message.From = <email>; message.To = <email>; 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.

25

.NET Technical FAQs


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. Is it possible to prevent a browser from caching an ASPX page? Just call SetNoStore on the HttpCachePolicy object exposed through the Response object's Cache property, as demonstrated here: <%@ 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 prevents caching of a Web page that shows the current time. What does AspCompat="true" mean and when should I use it? 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 access intrinsic ASP objects such as Request and Response. The following directive sets AspCompat to true:

26

.NET Technical FAQs

<%@ Page AspCompat="true" %> Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available to the COM components by placing unmanaged wrappers around the equivalent ASP.NET objects. Second, it improves the performance of calls 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" forces ASP.NET request threads into singlethreaded 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 to true if your page uses no COM objects or if it uses COM objects that don't access ASP intrinsic objects and that are registered ThreadingModel=Free or ThreadingModel=Both. Explain the differences between Server-side and Client-side code? Server side scripting means that all the script will be executed by the server and interpreted as needed. ASP doesn't have some of the functionality like sockets, uploading, etc. For these you have to make a custom components usually in VB or VC+ +. Client side scripting means that the script will be executed immediately in the browser such as form field validation, clock, email validation, etc. Client side scripting is usually done in VBScript or JavaScript. Download time, browser compatibility, and visible code - since JavaScript and VBScript code is included in the HTML page, then anyone can see the code by viewing the page source. Also a possible security hazards for the client computer. What type of code (server or client) is found in a Code-Behind class? C# Should validation (did the user enter a real date) occur server-side or client-side? Why? Client-side validation because there is no need to request a server side date when you could obtain a date from the client machine. What are ASP.NET Web Forms? How is this technology different than what is available though ASP? Web Forms are the heart and soul of ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the controls that are placed onto them. However, these UI elements render themselves in the appropriate markup language required by the request, e.g. HTML. If you use Microsoft Visual Studio .NET, you will also get the familiar drag-and-drop interface used to create your UI for your Web application. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they're difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.

27

.NET Technical FAQs


How can you provide an alternating color scheme in a Repeater control? AlternatingItemTemplate Like the ItemTemplate element, but rendered for every other row (alternating items) in the Repeater control. You can specify a different appearance for the AlternatingItemTemplate element by setting its style properties. Which template must you provide, in order to display data in a Repeater control? ItemTemplate What event handlers can I include in Global.asax? Application_Start,Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed, Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute, Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache, Session_Start,Session_End You can optionally include "On" in any of method names. For example, you can name a BeginRequest event handler.Application_BeginRequest or Application_OnBeginRequest.You can also include event handlers in Global.asax for events fired by custom HTTP modules.Note that not all of the event handlers make sense for Web Services (they're designed for ASP.NET applications in general, whereas .NET XML Web Services are specialized instances of an ASP.NET app). For example, the Application_AuthenticateRequest and Application_AuthorizeRequest events are designed to be used with ASP.NET Forms authentication. What is different b/w webconfig.xml & Machineconfig.xml Web.config & machine.config both are configuration files.Web.config contains settings specific to an application where as machine.config contains settings to a computer. The Configuration system first searches settings in machine.config file & then looks in application configuration files.Web.config, can appear in multiple directories on an ASP.NET Web application server. Each Web.config file applies configuration settings to its own directory and all child directories below it. There is only Machine.config file on a web server. If I'm developing an application that must accomodate multiple security levels though secure login and my ASP.NET web appplication is spanned across three web-servers (using round-robbin load balancing) what would be the best approach to maintain login-in state for the users? Use the state server or store the state in the database. This can be easily done through simple setting change in the web.config. <SESSIONSTATE StateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1; user id=sa; password=" cookieless="false" timeout="30" /> You can specify mode as stateserver or sqlserver. Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one. "One of ASP.NET's most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the request in a custom HTTP module.

28

.NET Technical FAQs


How do you turn off cookies for one page in your site? Since no Page Level directive is present, I am afraid that cant be done. How do you create a permanent cookie? Permanent cookies are available until a specified expiration date, and are stored on the hard disk.So Set the 'Expires' property any value greater than DataTime.MinValue with respect to the current datetime. If u want the cookie which never expires set its Expires property equal to DateTime.maxValue. Which method do you use to redirect the user to another page without performing a round trip to the client? Server.Transfer and Server.Execute What property do you have to set to tell the grid which page to go to when using the Pager object? CurrentPageIndex Should validation (did the user enter a real date) occur server-side or client-side? Why? It should occur both at client-side and Server side.By using expression validator control with the specified expression ie.. the regular expression provides the facility of only validatating the date specified is in the correct format or not. But for checking the date where it is the real data or not should be done at the server side, by getting the system date ranges and checking the date whether it is in between that range or not. What does the "EnableViewState" property do? Why would I want it on or off? Enable ViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not. For example, if you are binding a control to data on every round trip, then you do not need the control to maintain it's view state, since you will wipe out any re-populated data in any case. ViewState is enabled for all server controls by default. To disable it, set the EnableViewState property of the control to false. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other? Server.Transfer() : client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist accros the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive. Response.Dedirect() :client know the physical location (page name and query string as well). Context.Items loses the persisitance when nevigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but they're difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.

29

.NET Technical FAQs


Can you give an example of when it would be appropriate to use a web service as opposed to a non-serviced .NET component? Communicating through a Firewall When building a distributed application with 100s/1000s of users spread over multiple locations, there is always the problem of communicating between client and server because of firewalls and proxy servers. Exposing your middle tier components as Web Services and invoking the directly from a Windows UI is a very valid option. Application Integration When integrating applications written in various languages and running on disparate systems. Or even applications running on the same platform that have been written by separate vendors. Business-to-Business Integration This is an enabler for B2B intergtation which allows one to expose vital business processes to authorized supplier and customers. An example would be exposing electronic ordering and invoicing, allowing customers to send you purchase orders and suppliers to send you invoices electronically. Software Reuse This takes place at multiple levels. Code Reuse at the Source code level or binary componet-based resuse. The limiting factor here is that you can reuse the code but not the data behind it. Webservice overcome this limitation. A scenario could be when you are building an app that aggregates the functionality of serveral other Applicatons. Each of these functions could be performed by individual apps, but there is value in perhaps combining the the multiple apps to present a unifiend view in a Portal or Intranet. When not to use Web Services: Single machine Applicatons When the apps are running on the same machine and need to communicate with each other use a native API. You also have the options of using component technologies such as COM or .NET Componets as there is very little overhead. Homogeneous Applications on a LAN If you have Win32 or Winforms apps that want to communicate to their server counterpart. It is much more efficient to use DCOM in the case of Win32 apps and .NET Remoting in the case of .NET Apps Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines? The Application_Start event is guaranteed to occur only once throughout the lifetime of the application. It's a good place to initialize global variables. For example, you might want to retrieve a list of products from a database table and place the list in application state or the Cache object. SessionStateModule exposes both Session_Start and Session_End events. What are the advantages and disadvantages of viewstate? The primary advantages of the ViewState feature in ASP.NET are: 1. Simplicity. There is no need to write possibly complex code to store form data between page submissions. 2. Flexibility. It is possible to enable, configure, and disable ViewState on a control-by-control basis, choosing to persist the values of some fields but not others. There are, however a few disadvantages that are worth pointing out: 1. Does not track across pages. ViewState information does not automatically transfer from page to page. With the session approach, values can be stored in the session and accessed from other pages. This is not possible with ViewState, so storing data into the session must be done explicitly. 2. ViewState is not suitable for transferring data for back-end systems. That is, data still has to be transferred to the back end using some form of data object.

30

.NET Technical FAQs


Describe session handling in a webfarm, how does it work and what are the limits? ASP.NET Session supports storing of session data in 3 ways, i] in In-Process ( in the same memory that ASP.NET uses) , ii] out-of-process using Windows NT Service )in separate memory from ASP.NET ) or iii] in SQL Server (persistent storage). Both the Windows Service and SQL Server solution support a webfarm scenario where all the web-servers can be configured to share common session state store. 1. Windows Service : We can start this service by Start | Control Panel | Administrative Tools | Services | . In that we service names ASP.NET State Service. We can start or stop service by manually or configure to start automatically. Then we have to configure our web.config file <CONFIGURATION><configuration> <system.web> <SessionState mode = StateServer stateConnectionString = tcpip=127.0.0.1:42424 stateNetworkTimeout = 10 sqlConnectionString=data source = 127.0.0.1; uid=sa;pwd= cookieless =Flase timeout= 20 /> </system.web> </configuration> </SYSTEM.WEB> </CONFIGURATION> Here ASP.Net Session is directed to use Windows Service for state management on local server (address : 127.0.0.1 is TCP/IP loop-back address). The default port is 42424. we can configure to any port but for that we have to manually edit the registry. Follow these simple steps - In a webfarm make sure you have the same config file in all your web servers. - Also make sure your objects are serializable. - For session state to be maintained across different web servers in the webfarm, the application path of the web-site in the IIS

Metabase should be identical in all the web-servers in the webfarm. Which template must you provide, in order to display data in a Repeater control? You have to use the ItemTemplate to Display data. Syntax is as follows, < ItemTemplate > < div class =rItem > < img src=images/<%# Container.DataItem(ImageURL)%> hspace=10 /> < b > <% # Container.DataItem(Title)%> < /div > < ItemTemplate > How can you provide an alternating color scheme in a Repeater control? Using the AlternatintItemTemplate

31

.NET Technical FAQs


What property must you set, and what method must you call in your code, in order to bind the data from some data source to the Repeater control? Set the DataMember property to the name of the table to bind to. (If this property is not set, by default the first table in the dataset is used.) DataBind method, use this method to bind data from a source to a server control. This method is commonly used after retrieving a data set through a database query. What method do you use to explicitly kill a user s session? You can dump (Kill) the session yourself by calling the method Session.Abandon. ASP.NET automatically deletes a user's Session object, dumping its contents, after it has been idle for a configurable timeout interval. This interval, in minutes, is set in the <SESSIONSTATE>section of the web.config file. The default is 20 minutes. How do you turn off cookies for one page in your site? Use Cookie.Discard property, Gets or sets the discard flag set by the server. When true, this property instructs the client application not to save the Cookie on the user's hard disk when a session ends. Which two properties are on every validation control? We have two common properties for every validation controls 1. Control to Validate, 2. Error Message. What tags do you need to add within the asp:datagrid tags to bind columns manually? < asp:DataGrid id="dgCart" AutoGenerateColumns="False" CellPadding="4" Width="448px" runat="server" > < Columns > < asp:ButtonColumn HeaderText="SELECT" Text="SELECT" CommandName="select" >< /asp:ButtonColumn > < asp:BoundColumn DataField="ProductId" HeaderText="Product ID" >< /asp:BoundColumn > < asp:BoundColumn DataField="ProductName" HeaderText="Product Name" >< /asp:BoundColumn > < asp:BoundColumn DataField="UnitPrice" HeaderText="UnitPrice" >< /asp:BoundColumn > < /Columns > < /asp:DataGrid > How do you create a permanent cookie? Permanent cookies are the ones that are most useful. Permanent cookies are available until a specified expiration date, and are stored on the hard disk. The location of cookies differs with each browser, but this doesnt matter, as this is all handled by your browser and the server. If you want to create a permanent cookie called Name with a value of Nigel, which expires in one month, youd use the following code Response.Cookies ("Name") = "Nigel" Response.Cookies ("Name"). Expires = DateAdd ("m", 1, Now ()) What tag do you use to add a hyperlink column to the DataGrid? < asp:HyperLinkColumn > </ asp:HyperLinkColumn> Which method do you use to redirect the user to another page without performing a round trip to the client? Server.transfer

32

.NET Technical FAQs


What is the transport protocol you use to call a Web service SOAP ? HTTP Protocol Explain role based security ? Role Based Security lets you identify groups of users to allow or deny based on their role in the organization.In Windows NT and Windows XP, roles map to names used to identify user groups. Windows defines several built-in groups, including Administrators, Users, and Guests.To allow or deny access to certain groups of users, add the <ROLES>element to the authorization list in your Web application's Web.config file.e.g. <AUTHORIZATION>< authorization > < allow roles="Domain Name\Administrators" / > < !-- Allow Administrators in domain. -- > < deny users="*" / > < !-- Deny anyone else. -- > < /authorization > What is validationsummary server control?where it is used? The ValidationSummary control allows you to summarize the error messages from all validation controls on a Web page in a single location. The summary can be displayed as a list, a bulleted list, or a single paragraph, based on the value of the DisplayMode property. The error message displayed in the ValidationSummary control for each validation control on the page is specified by the ErrorMessage property of each validation control. If the ErrorMessage property of the validation control is not set, no error message is displayed in the ValidationSummary control for that validation control. You can also specify a custom title in the heading section of the ValidationSummary control by setting the HeaderText property. You can control whether the ValidationSummary control is displayed or hidden by setting the ShowSummary property. The summary can also be displayed in a message box by setting the ShowMessageBox property to true. What is the sequence of operation takes place when a page is loaded? BeginTranaction - only if the request is transacted Init - every time a page is processed LoadViewState - Only on postback ProcessPostData1 - Only on postback Load - every time ProcessData2 - Only on Postback RaiseChangedEvent - Only on Postback RaisePostBackEvent - Only on Postback PreRender - everytime BuildTraceTree - only if tracing is enabled SaveViewState - every time Render - Everytime End Transaction - only if the request is transacted Trace.EndRequest - only when tracing is enabled UnloadRecursive - Every request Difference between asp and asp.net? "ASP (Active Server Pages) and ASP.NET are both server side technologies for building web sites and web applications, ASP.NET is Managed compiled code - asp is interpreted. and ASP.net is fully Object oriented. ASP.NET has been entirely rearchitected to provide a highly productive programming experience based on the .NET Framework, and a robust infrastructure for building reliable and scalable web applications."

33

.NET Technical FAQs


Name the validation control available in asp.net? RequiredField, RangeValidator,RegularExpression,Custom validator,compare Validator What are the various ways of securing a web site that could prevent from hacking etc .. ? 1) Authentication/Authorization 2) Encryption/Decryption 3) Maintaining web servers outside the corporate firewall. etc., What is the difference between in-proc and out-of-proc? An inproc is one which runs in the same process area as that of the client giving tha advantage of speed but the disadvantage of stability becoz if it crashes it takes the client application also with it.Outproc is one which works outside the clients memory thus giving stability to the client, but we have to compromise a bit on speed. When youre running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003? On Windows 2003 (IIS 6.0) running in native mode, the component is running within the w3wp.exe process associated with the application pool which has been configured for the web application containing the component. On Windows 2003 in IIS 5.0 emulation mode, 2000, or XP, it's running within the IIS helper process whose name I do not remember, it being quite a while since I last used IIS 5.0. What does aspnet_regiis -i do ? Aspnet_regiis.exe is The ASP.NET IIS Registration tool allows an administrator or installation program to easily update the script maps for an ASP.NET application to point to the ASP.NET ISAPI version associated with the tool. The tool can also be used to display the status of all installed versions of ASP. NET, register the ASP.NET version coupled with the tool, create client-script directories, and perform other configuration operations. When multiple versions of the .NET Framework are executing side-by-side on a single computer, the ASP.NET ISAPI version mapped to an ASP.NET application determines which version of the common language runtime is used for the application. The tool can be launched with a set of optional parameters. Option "i" Installs the version of ASP.NET associated with Aspnet_regiis.exe and updates the script maps at the IIS metabase root and below. Note that only applications that are currently mapped to an earlier version of ASP.NET are affected What is a PostBack? The process in which a Web page sends data back to the same page on the server. What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState? ViewState is the mechanism ASP.NET uses to keep track of server control state values that don't otherwise post back as part of the HTTP form. ViewState Maintains the UI State of a Page ViewState is base64-encoded.

34

.NET Technical FAQs


It is not encrypted but it can be encrypted by setting EnableViewStatMAC="true" & setting the machineKey validation type to 3DES. If you want to NOT maintain the ViewState, include the directive < %@ Page EnableViewState="false" % > at the top of an .aspx page or add the attribute EnableViewState="false" to any control. What is the < machinekey > element and what two ASP.NET technologies is it used for? Configures keys to use for encryption and decryption of forms authentication cookie data and view state data, and for verification of out-of-process session state identification.There fore 2 ASP.Net technique in which it is used are Encryption/Decryption & Verification What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each? ASP.NET provides three distinct ways to store session data for your application: in-process session state, out-of-process session state as a Windows service, and out-of-process session state in a SQL Server database. Each has it advantages. 1.In-process session-state mode Limitations: * When using the in-process session-state mode, session-state data is lost if aspnet_wp.exe or the application domain restarts. * If you enable Web garden mode in the < processModel > element of the application's Web.config file, do not use in-process session-state mode. Otherwise, random data loss can occur. Advantages: * in-process session state is by far the fastest solution. If you are storing only small amounts of volatile data in session state, it is recommended that you use the in-process provider. 2. The State Server simply stores session state in memory when in out-of-proc mode. In this mode the worker process talks directly to the State Server 3. SQL mode, session states are stored in a SQL Server database and the worker process talks directly to SQL. The ASP.NET worker processes are then able to take advantage of this simple storage service by serializing and saving (using .NET serialization services) all objects within a client's Session collection at the end of each Web request Both these out-of-process solutions are useful primarily if you scale your application across multiple processors or multiple computers, or where data cannot be lost if a server or process is restarted. What is the difference between HTTP-Post and HTTP-Get? As their names imply, both HTTP GET and HTTP POST use HTTP as their underlying protocol. Both of these methods encode request parameters as name/value pairs in the HTTP request. The GET method creates a query string and appends it to the script's URL on the server that handles the request. The POST method creates a name/value pairs that are passed in the body of the HTTP request message.

35

.NET Technical FAQs


Name and describe some HTTP Status Codes and what they express to the requesting client. When users try to access content on a server that is running Internet Information Services (IIS) through HTTP or File Transfer Protocol (FTP), IIS returns a numeric code that indicates the status of the request. This status code is recorded in the IIS log, and it may also be displayed in the Web browser or FTP client. The status code can indicate whether a particular request is successful or unsuccessful and can also reveal the exact reason why a request is unsuccessful. There are 5 groups ranging from 1xx - 5xx of http status codes exists. 101 - Switching protocols. 200 - OK. The client request has succeeded 302 - Object moved. 400 - Bad request. 500.13 - Web server is too busy. Explain < @OutputCache% > and the usage of VaryByParam, VaryByHeader. OutputCache is used to control the caching policies of an ASP.NET page or user control. To cache a page @OutputCache directive should be defined as follows < %@ OutputCache Duration="100" VaryByParam="none" % > VaryByParam: A semicolon-separated list of strings used to vary the output cache. By default, these strings correspond to a query string value sent with GET method attributes, or a parameter sent using the POST method. When this attribute is set to multiple parameters, the output cache contains a different version of the requested document for each specified parameter. Possible values include none, *, and any valid query string or POST parameter name. VaryByHeader: A semicolon-separated list of HTTP headers used to vary the output cache. When this attribute is set to multiple headers, the output cache contains a different version of the requested document for each specified header.

C# and VB.NET
Explain the differences between Server-side and Client-side code? Server side code executes on the server.For this to occur page has to be submitted or posted back.Events fired by the controls are executed on the server.Client side code executes in the browser of the client without submitting the page. e.g. In ASP.NET for webcontrols like asp:button the click event of the button is executed on the server hence the event handler for the same in a part of the code-behind (server-side code). Along the server-side code events one can also attach client side events which are executed in the clients browser i.e. javascript events. How does VB.NET/C# achieve polymorphism? Polymorphism is also achieved through interfaces. Like abstract classes, interfaces also describe the methods that a class needs to implement. The difference between abstract classes and interfaces is that abstract classes always act as a base class of the related classes in the class hierarchy. For example, consider a hierarchy-car and truck classes derived from fourwheeler class; the classes two-wheeler and four-wheeler derived from an abstract class vehicle. So, the class 'vehicle' is the base class in the class hierarchy. On the other hand dissimilar classes can implement one interface. For example, there is an interface that compares two objects. This interface can be implemented by the classes like box, person and string, which are unrelated to each other. C# allows multiple interface inheritance. It means that a class can implement more than one interface. The methods declared in an interface are implicitly abstract. If a class implements an interface, it becomes mandatory for the class to override all the methods declared in the interface, otherwise the derived class would become abstract.

36

.NET Technical FAQs


Can you explain what inheritance is and an example of when you might use it? The savingaccount class has two data members-accno that stores account number, and trans that keeps track of the number of transactions. We can create an object of savingaccount class as shown below. savingaccount s = new savingaccount ( "Amar", 5600.00f ) ; From the constructor of savingaccount class we have called the two-argument constructor of the account class using the base keyword and passed the name and balance to this constructor using which the data member's name and balance are initialised. We can write our own definition of a method that already exists in a base class. This is called method overriding. We have overridden the deposit( ) and withdraw( ) methods in the savingaccount class so that we can make sure that each account maintains a minimum balance of Rs. 500 and the total number of transactions do not exceed 10. From these methods we have called the base class's methods to update the balance using the base keyword. We have also overridden the display( ) method to display additional information, i.e. account number. Working of currentaccount class is more or less similar to that of savingaccount class. Using the derived class's object, if we call a method that is not overridden in the derived class, the base class method gets executed. Using derived class's object we can call base class's methods, but the reverse is not allowed. Unlike C++, C# does not support multiple inheritance. So, in C# every class has exactly one base class. Now, suppose we declare reference to the base class and store in it the address of instance of derived class as shown below. account a1 = new savingaccount ( "Amar", 5600.00f ) ; account a2 = new currentaccount ( "MyCompany Pvt. Ltd.", 126000.00f) ; Such a situation arises when we have to decide at run-time a method of which class in a class hierarchy should get called. Using a1 and a2, suppose we call the method display( ), ideally the method of derived class should get called. But it is the method of base class that gets called. This is because the compiler considers the type of reference (account in this case) and resolves the method call. So, to call the proper method we must make a small change in our program. We must use the virtual keyword while defining the methods in base class as shown below. public virtual void display( ) { } We must declare the methods as virtual if they are going to be overridden in derived class. To override a virtual method in derived classes we must use the override keyword as given below. public override void display( ) { } Now it is ensured that when we call the methods using upcasted reference, it is the derived class's method that would get called. Actually, when we declare a virtual method, while calling it, the compiler considers the contents of the reference rather than its type. If we don't want to override base class's virtual method, we can declare it with new modifier in derived class. The new modifier indicates that the method is new to this class and is not an override of a base class method.

37

.NET Technical FAQs


How would you implement inheritance using VB.NET/C#? When we set out to implement a class using inheritance, we must first start with an existing class from which we will derive our new subclass. This existing class, or base class, may be part of the .NET system class library framework, it may be part of some other application or .NET assembly, or we may create it as part of our existing application. Once we have a base class, we can then implement one or more subclasses based on that base class. Each of our subclasses will automatically have all of the methods, properties, and events of that base class ? including the implementation behind each method, property, and event. Our subclass can add new methods, properties, and events of its own - extending the original interface with new functionality. Additionally, a subclass can replace the methods and properties of the base class with its own new implementation - effectively overriding the original behavior and replacing it with new behaviors. Essentially inheritance is a way of merging functionality from an existing class into our new subclass. Inheritance also defines rules for how these methods, properties, and events can be merged. In VB.NET we can use implements keyword for inheritance, while in C# we can use the sign ( : ) between subclass and baseclass. How is a property designated as read-only? In VB.NET: Private mPropertyName as DataType Public ReadOnly Property PropertyName() As DataType Get Return mPropertyName End Get End Property In C# Private DataType mPropertyName; public returntype PropertyName { get{ //property implementation goes here return mPropertyName; } // Do not write the set implementation } What is hiding in CSharp ? Hiding is also called as Shadowing. This is the concept of Overriding the methods. It is a concept used in the Object Oriented Programming. E.g. public class ClassA { public virtual void MethodA() { Trace.WriteLine("ClassA Method"); } } public class ClassB : ClassA { public new void MethodA() { Trace.WriteLine("SubClass ClassB Method"); } }

38

.NET Technical FAQs


public class TopLevel { static void Main(string[] args) { TextWriter tw = Console.Out; Trace.Listeners.Add(new TextWriterTraceListener(tw)); ClassA obj = new ClassB(); obj.MethodA(); // Outputs Class A Method" ClassB obj1 = new ClassB(); obj.MethodA(); // Outputs SubClass ClassB Method } } What is the difference between an XML "Fragment" and an XML "Document." An XML fragment is an XML document with no single top-level root element. To put it simple it is a part (fragment) of a wellformed xml document. (node) Where as a well-formed xml document must have only one root element. What does it meant to say the canonical form of XML? "The purpose of Canonical XML is to define a standard format for an XML document. Canonical XML is a very strict XML syntax, which lets documents in canonical XML be compared directly. Using this strict syntax makes it easier to see whether two XML documents are the same. For example, a section of text in one document might read Black & White, whereas the same section of text might read Black & White in another document, and even in another. If you compare those three documents byte by byte, they'll be different. But if you write them all in canonical XML, which specifies every aspect of the syntax you can use, these three documents would all have the same version of this text (which would be Black & White) and could be compared without problem. This Comparison is especially critical when xml documents are digitally signed. The digital signal may be interpreted in different way and the document may be rejected. Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to solve? "The XML Information Set (Infoset) defines a data model for XML. The Infoset describes the abstract representation of an XML Document. Infoset is the generalized representation of the XML Document, which is primarily meant to act as a set of definitions used by XML technologies to formally describe what parts of an XML document they operate upon. The Document Object Model (DOM) is one technology for representing an XML Document in memory and to programmatically read, modify and manipulate a xml document. Infoset helps defining generalized standards on how to use XML that is not dependent or tied to a particular XML specification or API. The Infoset tells us what part of XML Document should be considered as significant information. Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why? Document Type Definition (DTD) describes a model or set of rules for an XML document. XML Schema Definition (XSD) also describes the structure of an XML document but XSDs are much more powerful. The disadvantage with the Document Type Definition is it doesnt support data types beyond the basic 10 primitive types. It cannot properly define the type of data contained by the tag. An Xml Schema provides an Object Oriented approach to defining the format of an xml document. The Xml schema support most basic programming types like integer, byte, string, float etc., We can also define complex types of our own which can be used to define a xml document.

39

.NET Technical FAQs

Xml Schemas are always preferred over DTDs as a document can be more precisely defined using the XML Schemas because of its rich support for data representation. Speaking of Boolean data types, what's different between C# and C/C++? There's no conversion between 0 and false, as well as any other number and true, like in C/C++. How do you convert a string into an integer in .NET? Int32.Parse(string) Can you declare a C++ type destructor in C# like ~MyClass()? Yes, but what's the point, since it will call Finalize(), and Finalize() has no guarantees when the memory will be cleaned up, plus, it introduces additional load on the garbage collector. What's different about namespace declaration when comparing that to package declaration in Java? No semicolon. What's the difference between const and readonly? The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants as in the following example: public static readonly uint l1 = (uint) DateTime.Now.Ticks; What does \a character do? On most systems, produces a rather annoying beep. Can you create enumerated data types in C#? Yes. What's different about switch statements in C#? No fall-throughs allowed. What happens when you encounter a continue statement inside the for loop? The code for the rest of the loop is ignored, the control is transferred back to the beginning of the loop. How can you sort the elements of the array in descending order? By calling Sort() and then Reverse() methods. Will finally block get executed if the exception had not occurred? Yes.

40

.NET Technical FAQs


What's the C# equivalent of C++ catch (), which was a catch-all statement for any possible exception? A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}. Can multiple catch blocks be executed? No, once the proper catch code fires off, the control is transferred to the finally block (if there are any), and then whatever follows the finally block. Why is it a bad idea to throw your own exceptions? Well, if at that point you know that an error has occurred, then why not write the proper code to handle that error instead of passing a new Exception object to the catch block? Throwing your own exceptions signifies some design flaws in the project. What's the difference between // comments, /* */ comments and /// comments? Single-line, multi-line and XML documentation comments. How do you generate documentation from the C# file commented properly with a command-line compiler? Compile it with a /doc switch. Can you change the value of a variable while debugging a C# application? Yes, if you are debugging via Visual Studio.NET, just go to Immediate window. What's the implicit name of the parameter that gets passed into the class' set method? Value, and it's datatype depends on whatever variable we're changing. How do you inherit from a class in C#? Place a colon and then the name of the base class. Notice that it's double colon in C++. Does C# support multiple inheritance? No, use interfaces instead. So how do you retrieve the customized properties of a .NET application from XML .config file? Can you automate this process? Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable. In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval. Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio? The designer will likely through it away, most of the code inside InitializeComponent is auto-generated.

41

.NET Technical FAQs


Where do you add an event handler? It's the Attributesproperty, the Add function inside that property. e.g. btnSubmit.Attributes.Add(""onMouseOver"",""someClientCode();"") What are jagged array? First lets us answer the question that what an array is? The dictionary meaning of array is an orderly arrangement or sequential arrangement of elements. In computer science term: An array is a data structure that contains a number of variables, which are accessed through computed indices. The variables contained in an array, also called the elements of the array, are all of the same type, and this type is called the element type of the array. An array has a rank that determines the number of indices associated with each array element. The rank of an array is also referred to as the dimensions of the array. An array with a rank of one is called a single-dimensional array. An array with a rank greater than one is called a multi-dimensional array. Specific sized multidimensional arrays are often referred to as twodimensional arrays, three-dimensional arrays, and so on. Now let us answer What are jagged arrays? A jagged array is an array whose elements are arrays. The elements of jagged array can be of different dimensions and sizes. A jagged array is sometimes called as array-of-arrays. It is called jagged because each of its rows is of different size so the final or graphical representation is not a square. When you create a jagged array you declare the number of rows in your array. Each row will hold an array that will be on any length. Before filling the values in the inner arrays you must declare them. Jagged array declaration in C#: For e.g. : int [] [] myJaggedArray = new int [3][]; Declaration of inner arrays: myJaggedArray[0] = new int[5] ; // First inner array will be of length 5. myJaggedArray[1] = new int[4] ; // Second inner array will be of length 4. myJaggedArray[2] = new int[3] ; // Third inner array will be of length 3. Now to access third element of second row we write: int value = myJaggedArray[1][2]; Note that while declaring the array the second dimension is not supplied because this you will declare later on in the code. Jagged array are created out of single dimensional arrays so be careful while using them. Dont confuse it with multidimensional arrays because unlike them jagged arrays are not rectangular arrays. For more information on arrays: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/csref/html/vclrfarrayspg.asp What is a delegate, why should you use it and how do you call it ? A delegate is a reference type that refers to a Shared method of a type or to an instance method of an object. Delegate is like a function pointer in C and C++. Pointers are used to store the address of a thing. Delegate lets some other code call your function without needing to know where your function is actually located. All events in .NET actually use delegates in the background to wire up events. Events are really just a modified form of a delegate.

42

.NET Technical FAQs


It should give you an idea of some different areas in which delegates may be appropriate: They enable callback functionality in multi-tier applications as demonstrated in the examples above. <o:p></o:p> The CacheItemRemoveCallback delegate can be used in ASP.NET to keep cached information up to date. When the cached information is removed for any reason, the associated callback is exercised and could contain a reload of the cached information. <o:p></o:p> Use delegates to facilitate asynchronous processing for methods that do not offer asynchronous behavior. Events use delegates so clients can give the application events to call when the event is fired. Exposing custom events within your applications requires the use of delegates. How does the XmlSerializer work? XmlSerializer in the .NET Framework is a great tool to convert Xml into runtime objects and vice versa If you define integer variable and a object variable and a structure then how those will be plotted in memory. Integer , structure System.ValueType -- Allocated memory on stack , infact integer is primitive type recognized and allocated memory by compiler itself . Infact , System.Int32 definition is as follows : [C#] [Serializable] public struct Int32 : IComparable, IFormattable, IConvertible So , its a struct by definition , which is the same case with various other value types . Object Base class , that is by default reference type , so at runtime JIT compiler allocates memory on the Heap Data structure . Reference types are defined as class , derived directly or indirectly by System.ReferenceType

43

Vous aimerez peut-être aussi