Wednesday, August 02, 2006

ASP.NET Page Life Cycle

Clear understanding of ASP.NET Page life cycle
http://blogs.crsw.com/mark/articles/471.aspx

  1. Constructor()
  2. AddParsedSubObject()
  3. DeterminePostBack()
  4. OnInit()
  5. LoadPageFromPersistenceMedium()
  6. LoadViewState()
  7. ProcessPostData()
  8. OnLoad()
  9. ProcessPostData()
  10. RaiseChangedEvents()
  11. RaisePostBackEvent()
  12. OnPrerender()
  13. SaveViewState()
  14. SaveViewStatetoPersistenceMedium()
  15. OnPrerender()
  16. Render()
  17. Dispose()

Few more general questions in .NET

All these questions are taken from http://blogs.crsw.com/mark/articles/252.aspx

  • CCW : Com Callable wrapper.
  • RCW : RUN time callable wrapper.
  • foo.gettype() ,Gettype(foo)
  • ASP . Interprepter.. use the script engine but ASP.Net Compiled
  • Microsoft Intermeidate lanaguage. which is the out put for all the .net supported languages after comiplation will produce. Appreciation for cross language support.
  • What base class do all Web Forms inherit from? System.Web.UI.Page
  • malloc, alloc, release
  • ASP.NET is a technology that provides a framework for developing .NET based web applications.
  • ASP.NET is not a platform independen language. ASP.NET is more of a technology that provides a framework for building web applications. ASP.NET provides the reources needed to dynamically deliver html content (pages) to the end user. ASP.NET can leverage languages such as C#, VB.NET, and javascript to help provide a reliable, high perfofmance, and secure web application.
  • .net framework is independent because msil is independent can be run anywhere. but it is platform dependent because msil wil be converted to native code which is understandable by windows.
  • What is serialization, how it works in .NET?
  • What should one do to make class serializable?
  • What exactly is being serialized when you perform serialization?
  • scope in C#
  • The primary purpose of XML serialization in the .NET Framework is to enable the conversion of XML documents and streams to common language runtime objects and vice versa. Serialization of XML to common language runtime objects enables one to convert XML documents into a form where they are easier to process using conventional programming languages. On the other hand, serialization of objects to XML facilitates persisting or transporting the state of such objects in an open, standards compliant and platform agnostic manner.
  • Serialization is the process of converting an object or a con-nected graph of objects into a contiguous stream of bytes. Deserialization is the process of converting a contiguous stream of bytes back into its graph of connected objects. The ability to convert objects to and from a byte stream is an incredibly useful mechanism. Here are some examples:
  • An application's state (object graph) can easily be saved in a disk file or database and then restored the next time the application is run. ASP.NET saves and restores session state by way of serialization and deserialization.
  • A set of objects can easily be copied to the system's clipboard and then pasted into the same or another application. In fact, Windows® Forms uses this procedure. • A set of objects can be cloned and set aside as a backup while a user manipulates the main set of objects.
  • A set of objects can easily be sent over the network to a process running on another machine. The Microsoft® .NET Framework remoting architecture serializes and deserializes objects that are marshaled by value. Why would you want to use serialization? The two most important reasons are to persist the state of an object to a storage medium so an exact copy can be recreated at a later stage, and to send the object by value from one application domain to another.
  • Static methods
  • copyto method makes a deep copy and clone method makes a shallow copy
  • What is web garden?
  • What is object pooling?
  • Tell some thing about IIS isolation levels.
  • Dispose is the method, which we call usually when we want the object to be garbage collected. If u r calling Dispose() on inbuilt classes like Form, It'll call a method Finalize() method, which will usually used to cleanup any resources used with in the form. With in this Finalize method, we call the garbage collector to recycle the memory. So, when u r using dispose method, it is used to mark the object to Garbage Collectable. Calling the Dispose dose't means, that object will b garbage collected immidiately. GC will monitor the Managed memory for objects Marked 4 garbage collectable. The recycling of memory depends on when the GC will pay the visit. Purely the Dispose method is not used for reseting the values in the object. It is used to mark the Object to b collected by the GC
  • What are the different types of assemblies – name them?Private Public/Shared Satellite assembly
  • This Global Assembly Cache(GAC) stores .NET assemblies to be shared by several applications on that computer.
  • How many ways can we maintain the state of a page? 1.Client Side [ Query string, hidden variables, view state,cookies] 2.Server side [application , session, database]
  • What is the purpose of a private constructor? [Rama Naresh Talluri] Prevent the creation of instance for a class
  • Differentiate Dispose and Finalize. [Rama Naresh Talluri] Finalize is called by the Garbage Collector, and the state of manage objects cannot be guaranteed, so we can not reference them. Also, we cannot determine when the GC will run, and which objects it will Finalize. Dispose is called by the programmer, and is used to dispose of managed and unmanaged objects. Within we dispose method, we release all of our resources and call GC.SuppressFinalize as we have done the work of the GC.
  • What is the purpose of Singleton pattern? [Rama Naresh Talluri] Singleton pattern is used to make sure that only one instance of a given class exists.
  • What is the difference between well formed and valid xml document ?
  • 1. Explain about Normalization?
  • 2. What is the difference between union & union all?
  • 3. What kind of transactions can handled?
  • 4. temporay tables use & how we can manage?
  • 5. perfomance tuning steps? 6. Difference btn method overload / override?
  • 7. When Garbage collector come into picture?
  • 8. Difference btn refernce & value types?
  • 9. boxing / unboxing in ASP.NET
  • 10. assemblies
  • 11. What manifest file contains?
  • 12. MSIL
  • 13. JIT
  • 14. clas vs module
  • 15. dataadapter
  • 16. dataset
  • 17. ado.net objects
  • 18. difference btn and, and also
  • 19. dataset.copy & dataset.clone
  • 20. code access security
  • 21. finalization
  • 22. strogn type dataset

Excellent Questions

Net topics

1. Define what is meant by the term “data structure”?

A data structure is an abstract struct or class that is used to organize info and provide various manipulations on their enclosed data. The most common data structure would be array, but there are many well-known structures in .NET including hashtables, queues, and other collection classes (even custom) that can be made into Binary Search Trees and other usable data structures for the specific programming problem at hand.

2. What is MSIL (Microsoft Intermediate Language) and how is it generated? MSIL is machine-independant code (similar to java bytecode in and ASM sort of way…) that describes instructions of a program. The main purpose of MSIL is to run implementations of the programs defined metadata (which is stored in an assembly with the specific AppDomain) so that the CLR can utilize this ‘bluprint’ and bring a program to life. Metadata and MSIL is generated by a compiler, and can be inspected through ILDASM or .NET Reflector (third-party free program). For example csc.exe is the compiler for CSharp code.

3. What is Garbage Collection?

Garbage Collection is a hassle-free way to free up assigned memory spaces during the runtime execution of a managed code program. By using Garbage Collection (in a enhanced implementation than Java does..) we can write managed code programs without worrying about the number of objects we are instantiated at runtime or the proper disposal of those objects. The Garbage collector will determine when the object is no longer going to be used within a programs execution, and will flag it for ‘pickup’, however pickup does not actually occur until additional memory is needed by the program, and hence garbage collection can occur randomly throughout the execution lifetime. You can equate and think about this in terms of the benefits of being able to program against heap memory versus stack memory. The awesome thing about GC is that it frees us from worries of dangling pointers, circular references, or memory leaks (and blue screens).

4. What is Serialization? What 2 formats does dot net provide?

Serialization is a means in which to take and object, and be able to map its structure or class graph into a stream. The purpose of which normally is to transfer that object to another location, or persist custom obejects to some form of storage. .NET provides two main implementation classes for serialization.. the XML Soap Formatter and the BinaryFormatter class. You must implement the IFormatter interface to actually write out to these streams using the Serialize or Deserialize methods, and you can mark classes unserializable or serializable using Attributes in your code.

5. What is the GAC (Global Assembly Cache) used for?

The GAC is a shared ‘dumpsite’ for assemblies you wish to strong-name and share across multiple app domains. This is a great way to shared common components (like rich-text box controls or custom mail classes). The GAC is used for this data store component sharing ability, as well as for storing code downloaded from the internet (in a private portion of the cache), and for storing native code versions of pre-JIT assemblies.

5. Is a String a value or reference type? What is the difference between the two? A String in .NET is an immutable object comprised of char objects. Since these objects last as constant throughout their instantiated lifetime (hence are immutable) they are treated as value types. Value types are usually simple types such as integers, floats, and other objects as opposed to user-defined types such as a customer object in a customers class. The major difference between value and reference types are how they are treated in allocated memory… value types are copied in memory and reference types are usually shallow-copied, basically a memory pointer of sorts points (or references) the memory address of the original object. Most reference types are shallow-copied unless specifically coded for a deep-copy implementation (as may be required in late-binding scenarios). The .NET framework takes care of most boxing and unboxing of types as required. In a value type, what the called method does with the incoming parameter doesn’t affect the variable passed down from the calling method. With a reference type, when the called method makes changes to the data through the reference, the changes are made to the original data.

C#

1. What are the as and is keywords used for?

‘is’ is used to check if an object is compatible with a given type against its run-time type, and ‘as’ is used to perform conversions between compatible types. The ‘as’ operator is used in an expression form, like “expression as type’

2. What is the using keyword used for?

Using is similar to the Java imports directive, which allows us to reference a namespace.. This allows us to refer to members of that namespace, without having to utilize its fully-qualified name. For example, if I want to use regular expressions features, I should add a using directive in order to access members of that namespace without their FQN. “using System.Text.RegularExpressions;” The keyword ‘using’ is overloaded however, and can be used as a statement for an object that wants to implement IDisposable.

3. What is the out and ref keyword used for in functions and how do they differ?

The out keyword is used for parameters assigned within the called method, and passed by reference back out of that called method.. the ref keyword is for parameters assigned prior to the call to that particular method (functions should be referred to as methods in .NET by the way…) and the parameter is being passed by reference, not by-value.

4. What is a delegate?

A delegate is a type that defines a methods signature so the delegate can hold and invoke a method of that same signature.. In the term of Chess pieces.. a delegate would be akin to a King’s Bishop.. who could hold or act on the King’s orders. Delegates are powerful mechanisms for the event model of .NET, and allows us to multicast delegates… that is allow us to raise multiple events or notify multiple delegates of an event, or event to raise events sequentially.

5. What is the difference between a struct and a class?

A struct (or structure) is lightweight compared to all the features of a class, basically because it is a value type, wherin a class is a reference type. We usually use structures for desirable semantics such when we want an assignment to copy a value rather than a reference.. Classes can have destructors, which structs cannot have, and classes can have parameterless constructors.. which structs cannot have. Stucts are sealed classes, but can implement interfaces like classes can.

Object Oriented Design principles

1. What is method overloading and method overriding?

Overloading a method generally refers to creating multiple signatures of that method, allowing us to call that method with differentiating parameters in order to run a differentiating operation. For example, a engine class might have one method for start() intended for a gasoline engine, and another method of start(nGlowPlugTime) meant for a diesel engine. In such case, the start() method would be overloaded. Overriding a method is when we want to take a base class definition of a method, and change the implementation details of that method in the derived class by rewriting it to suit our specifications. Essentially this goes hand-in-hand with the virtual and override keywords in .NET We can override abstract, virtual or override declared methods, but we could not override sealed classes for example.

2. Describe two uses of the new keyword in .NET.

The new operator is most often used to instantiate a new instance of an object (create new memory allocation on the heap and invoke constructors for that object). New can also be used as a modifier, in order to explicitly hide a derived class member from the base class… Such a implementation would look like new public void Start()

3. What is the difference between interfaces and inheritance?

Wow.. great question.. hehe… inheritance usually in .NET is thought of as a single-inheritance model, not multiple.. so for example my child could inherit my bad habits, but not both my own and my wife’s bad habits (We would have to override all those bad habits anyway..) interfaces are contracts that programmers should implement (in fact, they must implement) when creating a class. My best analogy for an interface is a standard Universal TV Remote Control.. although it can turn on any television, the actual implementation of that particular IR signal is dependent on the make/model of the TV you are trying to turn on.. hence the “ON” would be exposed as an interface… surely you would have to implement this interface in order to actually get the thing to really work. However interfaces can be utilized to get to a sort-of pseudo multiple inheritance model if utilized correctly and in written in proper fashion.

4. What is an abstract data type? How is one defined in C#? Abstract methods provide no actual implementation details, and an abstract data type, or abstract property, behave similar. An abstract inherited property could be overridden and implemented in a derived class by declaring that property with the override modifier. We define it in C# with the abstract modifier. Abstract data types are implicitly virtual, and hence could not be static members (static members are when a single instantiated object is constant throughout the application..)

5. What is polymorphism used for? Polymorphism is best described as multiple uses for a particular object. If I were to create a 35 in 1 tool for example, that particular tool has 35 polymorphic uses. Each of those uses could require a specific implementation (or contract) in order to achieve the desired results. For example, the Draw() method for shapes is polymorphic, depending on whether I would draw a circle, square, polyhedron, etc.. the method could indeed be used, hence it would need polymorphism. True polymorphism is generally a multiple-inheritance model, and hence you would need to turn to interfaces to achieve the desired results as opposed to simple inheritance which could be achieved by overloading the methods.

Databases T-SQL

1. What is the difference between HAVING and WHERE clauses? Having behaves like a where clause when improperly used, that is having should be used in a SELECT statement with a GROUP BY clause. WHERE is used to restrict the results returned, wherin having should be used to group results or restrict results by aggregate.

2. What is the difference between TRUNCATE and DELETE? I am a big fan of TRUNCATE… especially with MySQL, but it essentially is the same in SQLServer… it removes all the rows of a table without logging the individual deletions.. and it doesn’t have any WHERE clauses in its usage.. hence it is generally less resource-intensive, and surely faster than, DELETE. DELETE walks through all the rows one-by-one, yet truncate just deallocates the data pages used, usually with less locks on the database table.

3. What is an index? An index can be created on tables and views, and is like an index of a book, it lets the database quickly find the data it is indeed looking for in response to the given query. It contains keys that relate to storage locations of the individual data contained within columns for which the index is defined. Indexes open up critical database considerations in speed and execution and are best left to experienced DBA’s who understand the ramifications of the index, for example, indexing small tables or having a large number of indexes on a table could drastically affect performance.

4. What is a clustered and non-clustered index? A clustered index is one in which the logical order of the keys in the index equates to the physical order of the data rows in the DB. An indexed view is actually a clustered index that is unique for example. A clustered index needs to be explicitly created, generally before any nonclustered indexes. With nonclustered indexes, their physical order is independent of the index keys, and this is the default implementation of indexes.

5. What is an instead of trigger? A instead of trigger specifies it will be executed in replecement of the triggering SQL statement. In SLQ 2005, we can execute DDL triggers on DB schema, but instead of cannot be executed on DDL queries, only on DML T-SQL… and there can only be one instead-of instance per INSERT, UPDATE or DELETE. In addition, we could not replace the SQL statements in a DELETE with a cascade action, hence instead of would not be allowed in such a situation.

6. Given a table named User having a single nullable column named UserName, what is the SQL statement that will return a result set that contains the total number of non-NULL UserName? SELECT COUNT(ALL UserName) FROM User

ASP.Net

1. What is viewstate and where is it stored by default?

The viewstate is a page-level state preservation mechanism, most-often used between postbacks to persist the state of controls on the page. It is stored in encrypted hidden fields on the page (__VIEWSTATE__). There are multiple Page declaration attributed that can be used for the viewstate, including turning it on or off, encrypting it, allowing viewstate to persist for example on Server.Transfer requests, etc. It is a great lightweight persistence mechanism, but for pages that never change control state, or pages with very large data-intensive result sets.. the viewstate is best not employed.

2. What does the SmartNavigation page directive do? It doesn’t do anything anymore.. its deprecated… But what it had done in the past, is allow asp.net to return to the same control area on the page during a postback, to prevent users from scrolling again to a particular region of the page. It utilized a feature buit-in to IE5 that would remember the element focus and scroll position on a page. You will now see many SmartNavigation warnings in your VisualStudio error box on building older code on the new ASP.NET 2.0 framework about it’s deprecation.

3. What interface(s) do I need to implement when designing custom web controls that raises servers-side events? I believe you would have to implement the IDispose interface for sure to clean up after the page is unloaded, and perform any other final cleanup work. Usually custom server-side controls are developed to encapsulate reusable code so that a html tag can be dropped into a page and that custom control is brought to life (like a custom Web grid, etc.) By encapsulating the functionality we could respond to events and set the control properties, hence there should be a mechanism that ensures a custom-control is cleaning up after itself.. o IDispose would certainly fit the bill.

4. What are the 3 authentication types that ASP.Net supports?

The most common authentication method is Forms based authentication, followed by Windows-based authentication, and finally Passport authentication.. the former of which is under revision into the new Windows Live features and service set.. There is a fourth type of authentication really, that is NO authentication, which would rely on the inherit capabilities of IIS, or perhaps a custom-built http module that would run before the asp.net module is hit.. Custom modules would be extremely ineffective in a shared web farm situation for example, which would benefit from authenticating users under a centralized user credential service such as Microsoft Passport offers.

5. Between which page life cycles stages is the viewstate loaded?

The viewstate is loaded between the InitComplete event and Page_Load events.. in ASP.NET 1.x, you must wait for the Load event to start to safely write to any control viewstate. Ulitmately, the StateBag class of the framework is responsible for the viewstate that manages information, and it works like a dictionary collection class, allowing you to get and set data as appropriate.

ESRI Interview Questions

After grilling 8 interviews from 9am to 5pm, i was completely exhausted.
Here a few questions, I remember....
  • What is GAC
  • How to deploy an assembly
  • Exception handling(multiple catch statements)
  • Life cycle of a thread in java, web service
  • Difference between jsps and servlets
  • what is ngen.exe ?
  • dll hell?
  • What is CLR?
  • XML and XPath
  • Ajax

Friday, July 21, 2006

Excellent C# interview questions

Here is a link to excellent interview questions list......
Dont be suprised, if you see the same questions on the interview.....
http://blogs.crsw.com/mark/articles/252.aspx

Wednesday, July 12, 2006

Scotts Questions.....

All the questions below are from :
http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx

What Great .NET Developers Ought To Know

Everyone who writes code

Describe the difference between a Thread and a Process?
What is a Windows Service and how does its lifecycle differ from a "standard" EXE?
What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?
What is the difference between an EXE and a DLL?
What is strong-typing versus weak-typing? Which is preferred? Why?
Corillian's product is a "Component Container." Name at least 3 component containers that ship now with the Windows Server Family.
What is a PID? How is it useful when troubleshooting a system?
How many processes can listen on a single TCP/IP port?
What is the GAC? What problem does it solve?

Mid-Level .NET Developer

Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.
Describe what an Interface is and how it’s different from a Class.
What is Reflection?
What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?
Are the type system represented by XmlSchema and the CLS isomorphic?
Conceptually, what is the difference between early-binding and late-binding?
Is using Assembly.Load a static reference or dynamic reference?
When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?
What is an Asssembly Qualified Name? Is it a filename? How is it different?
Is this valid? Assembly.Load("foo.dll");
How is a strongly-named assembly different from one that isn’t strongly-named?
Can DateTimes be null?
What is the JIT? What is NGEN? What are limitations and benefits of each?
How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?
What is the difference between Finalize() and Dispose()?
How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?
What does this useful command line do? tasklist /m "mscor*"
What is the difference between in-proc and out-of-proc?
What technology enables out-of-proc communication in .NET?
When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?

Senior Developers/Architects

What’s wrong with a line like this? DateTime.Parse(myString);
What are PDBs? Where must they be located for debugging to work?
What is cyclomatic complexity and why is it important?
Write a standard lock() plus “double check” to create a critical section around a variable access.
What is FullTrust? Do GAC’ed assemblies have FullTrust?
What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?
What does this do? gacutil /l find /i "Corillian"
What does this do? sn -t foo.dll
What ports must be open for DCOM over a firewall? What is the purpose of Port 135?
Contrast OOP and SOA. What are tenets of each?
How does the XmlSerializer work? What ACL permissions does a process using it require?
Why is catch(Exception) almost always a bad idea?
What is the difference between Debug.Write and Trace.Write? When should each be used?
What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
Does JITting occur per-assembly or per-method? How does this affect the working set?
Contrast the use of an abstract base class against an interface?
What is the difference between a.Equals(b) and a == b?
In the context of a comparison, what is object identity versus object equivalence?
How would one do a deep copy in .NET?
Explain current thinking around IClonable.
What is boxing?
Is string a value type or a reference type?
What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?
Why are out parameters a bad idea in .NET? Are they?
Can attributes be placed on specific parameters to a method? Why is this useful?

C# Component Developers

Juxtapose the use of override with new. What is shadowing?
Explain the use of virtual, sealed, override, and abstract.
Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d
Explain the differences between public, protected, private and internal.
What benefit do you get from using a Primary Interop Assembly (PIA)?
By what mechanism does NUnit know what methods to test?
What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}
What is the difference between typeof(foo) and myFoo.GetType()?
Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?
What is this? Can this be used within a static method?

ASP.NET (UI) Developers

Describe how a browser-based Form POST becomes a Server-Side event like Button1_OnClick.
What is a PostBack?
What is ViewState? How is it encoded? Is it encrypted? Who uses ViewState?
What is the element and what two ASP.NET technologies is it used for?
What three Session State providers are available in ASP.NET 1.1? What are the pros and cons of each?
What is Web Gardening? How would using it affect a design?
Given one ASP.NET application, how many application objects does it have on a single proc box? A dual? A dual with Web Gardening enabled? How would this affect a design?
Are threads reused in ASP.NET between reqeusts? Does every HttpRequest get its own thread? Should you use Thread Local storage with ASP.NET?
Is the [ThreadStatic] attribute useful in ASP.NET? Are there side effects? Good or bad?
Give an example of how using an HttpHandler could simplify an existing design that serves Check Images from an .aspx page.
What kinds of events can an HttpModule subscribe to? What influence can they have on an implementation? What can be done without recompiling the ASP.NET Application?
Describe ways to present an arbitrary endpoint (URL) and route requests to that endpoint to ASP.NET.
Explain how cookies work. Give an example of Cookie abuse.
Explain the importance of HttpRequest.ValidateInput()?
What kind of data is passed via HTTP Headers?
Juxtapose the HTTP verbs GET and POST. What is HEAD?
Name and describe at least a half dozen HTTP Status Codes and what they express to the requesting client.
How does if-not-modified-since work? How can it be programmatically implemented with ASP.NET?Explain <@OutputCache%> and the usage of VaryByParam, VaryByHeader.
How does VaryByCustom work?
How would one implement ASP.NET HTML output caching, caching outgoing versions of pages generated via all values of q= except where q=5 (as in http://localhost/page.aspx?q=5)?

Developers using XML

What is the purpose of XML Namespaces?
When is the DOM appropriate for use? When is it not? Are there size limitations?
What is the WS-I Basic Profile and why is it important?
Write a small XML document that uses a default namespace and a qualified (prefixed) namespace. Include elements from both namespace.
What is the one fundamental difference between Elements and Attributes?
What is the difference between Well-Formed XML and Valid XML?
How would you validate XML using .NET?
Why is this almost always a bad idea? When is it a good idea? myXmlDocument.SelectNodes("//mynode");
Describe the difference between pull-style parsers (XmlReader) and eventing-readers (Sax)
What is the difference between XPathDocument and XmlDocument? Describe situations where one should be used over the other.
What is the difference between an XML "Fragment" and an XML "Document."
What does it meant to say “the canonical” form of XML?
Why is the XML InfoSet specification different from the Xml DOM? What does the InfoSet attempt to solve?
Contrast DTDs versus XSDs. What are their similarities and differences? Which is preferred and why?
Does System.Xml support DTDs? How?
Can any XML Schema be represented as an object graph? Vice versa?

ASP.NET

  • Describe the difference between a Thread and a Process?
  • What is a Windows Service and how does its lifecycle differ from a “standard” EXE?
  • What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?
  • What is the difference between an EXE and a DLL?
  • What is strong-typing versus weak-typing? Which is preferred? Why?
  • What’s wrong with a line like this? DateTime.Parse(myString
  • What are PDBs? Where must they be located for debugging to work?
  • What is cyclomatic complexity and why is it important?
  • Write a standard lock() plus double check to create a critical section around a variable access.
  • What is FullTrust? Do GAC’ed assemblies have FullTrust?
  • What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?
  • What does this do? gacutil /l find /i “about”
  • What does this do? sn -t foo.dll
  • What ports must be open for DCOM over a firewall? What is the purpose of Port 135?
    Contrast OOP and SOA. What are tenets of each
  • How does the XmlSerializer work? What ACL permissions does a process using it require?
  • Why is catch(Exception) almost always a bad idea?
  • What is the difference between Debug.Write and Trace.Write? When should each be used?
  • What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?
  • Does JITting occur per-assembly or per-method? How does this affect the working set?
  • Contrast the use of an abstract base class against an interface?
  • What is the difference between a.Equals(b) and a == b?
  • In the context of a comparison, what is object identity versus object equivalence?
  • How would one do a deep copy in .NET?
  • Explain current thinking around IClonable.
  • What is boxing?
  • Is string a value type or a reference type?

The following questions are taken from the link below

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

http://www.pkblogs.com/basittanveer/2006/05/aspnet-interview-questions.html

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

1. What is the difference between encoding and encryption? Which is easy to break? Can we disable the view state application wide? can we disable it on page wide? can we disable it for a control?

Ans: encoding is easy to break, we can disable it page wide and control level.

2. Can you read the View State? Disadvantage of a view state. ( asked to me in IFLEX Solutions)

Ans: Yes we can read the view state since it is encoded using base64 string, so it is easy to break it, we also have view state decoders ( http://www.pluralsight.com/toolcontent/ViewStateDecoder21.zip)

3. What is provider Model? (asked to me in mindlogicx , salsoft)

Ans: Provider model means that microsoft has provided a set of interfaces, a new vendor just needs to implement them and write the functionality for their software to work with MS. example SQL provider model, ODBC provider model, MySQL proviuder model.

4. Any idea of Enterprise library?

http://www.dotnetjunkies.com/Article/29EF3A4F-A0C2-4BB2-A215-8F87F100A9F9.dcik

5. Can we have multiple web.config files in a sigle web project? ( asked to me in IFLEX Solutions, salsoft)

Ans: Yes we can have them for each sub folders in the web project main folder.

6. Can we have more then one configuration file?

Ans: yes

7. What is the difference between syncronus and asyncronus?

Ans: syncronus means you are waiting for the responce to come back, while in the asyncronus you start with the next staement and whenever the results come back a call back function is called.

8. Difference between http and https? what is purpose of aspnet_wp.exe ? what is an ISAPI filter? what do you mean by HTTP Handler?

Ans: https means it is using SSL, aspnet_wp is the worker process that handles all the asp net requests, ISAPI filter helps the iis in identifying the request type and forwarding it to the appropriate handler.

9. what is side by side execution?

Ans: It means that we can have two dot net version running on the same server machine, and the application build in asp.net 1.1 will be server by dot net framework 1.1 and the applications build in asp.net 2.0 will be server by dot net framework 2.0.

10. can we have two different versions of dot net frameworks running on the same machine?

Ans: yes

11. Can we have an updateable view in SQL?

Ans: Yes

12. What is the difference between typed and untyped dataset?

Ans: typed data set contains the inforation of the db/table structure

Wednesday, June 07, 2006

iLand Diary Page

chek out the link to new poster of superman....
iLand Diary Page

Tuesday, June 06, 2006

DataList Events

  • A DataListItem instance is created.
  • The proper template is used to render the contents of the DataListItem. It's at this point that the DataList's SelectedIndex is checked to see whether the ItemTemplate should be used or if the SelectedItemTemplate should be used.
  • The DataList's ItemCreated event is raised.
  • The DataListItem's DataItem property is set to the current DataSource row, and the DataListItem's DataBind() method is called.
  • The DataList's ItemDataBound event is raised.

Wednesday, May 17, 2006

Abstract class and Interface

  • Abstract class cannot be instantiated but can be derived.An abstract class can contain abstract methods or non abstract methods. Abstract class cannot be sealed class
  • Abstract method cannot be private and should be declared in abstract class.
  • Abstract method is implicitly virtual
  • Abstract member cannot be static
  • All the members of an interface are implicitly abstract
  • All the members of an interface should be overridded.
  • A class can inherit only multiple interfaces but it can inherit one abstract class
  • An interface is not a class and has no implementation

Again 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.
  • 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.
  • 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 code-behind?
    Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing the code you want to debug, and set your breakpoints. Start the ASP.NET application. Go back to DbgClr, choose Debug Processes from the Tools menu, and select aspnet_wp.exe from the list of processes. (If aspnet_wp.exe doesn't appear in the list,check the "Show system processes" box.) Click the Attach button to attach to aspnet_wp.exe and begin debugging.
    Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can enable tell ASP.NET to build debug executables by placing a
    <%@ Page Debug="true" %>statement at the top of an ASPX file or a statement in a Web.config file.
  • Can a user browsing my Web site read my Web.config or Global.asax files?
    No. The 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.
  • 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" %>

More ASP.NET

  • From constructor to destructor (taking into consideration Dispose() and the concept of non-deterministic finalization), what the are events fired as part of the ASP.NET System.Web.UI.Page lifecycle. Why are they important? What interesting things can you do at each?
  • What are ASHX files? What are HttpHandlers? Where can they be configured?
  • What is needed to configure a new extension for use in ASP.NET? For example, what if I wanted my system to serve ASPX files with a *.jsp extension?
  • What events fire when binding data to a data grid? What are they good for?
  • Explain how PostBacks work, on both the client-side and server-side. How do I chain my own JavaScript into the client side without losing PostBack functionality?
  • How does ViewState work and why is it either useful or evil?
  • What is the OO relationship between an ASPX page and its CS/VB code behind file in ASP.NET 1.1? in 2.0?
  • What happens from the point an HTTP request is received on a TCP/IP port up until the Page fires the On_Load event?
  • How does IIS communicate at runtime with ASP.NET? Where is ASP.NET at runtime in IIS5? IIS6?
  • What is an assembly binding redirect? Where are the places an administrator or developer can affect how assembly binding policy is applied?
    Compare and contrast LoadLibrary(), CoCreateInstance(), CreateObject() and Assembly.Load().

Reference: http://www.hanselman.com/blog/ASPNETInterviewQuestions.aspx

ASP.NET Questions

Here are a few ASP.NET questions, which I found on the internet...Here is a link to to it...
http://blogs.crsw.com/mark/articles/254.aspx

1. Explain the differences between Server-side and Client-side code?
Server side code basically gets executed on the server (for example on a webserver) per request/call basis, while client side code gets executed and rendered on the client side (for example web browser as a platform) per response basis.

2. What type of code (server or client) is found in a Code-Behind class?
In the Code-behind class the server side code resides, and it generates the responses to the client appropriately while it gets called or requested.

3. Should validation (did the user enter a real date) occur server-side or client-side? Why?
That depends. In the up browsers (like IE 5.0 and up and Netscape 6.0) this would help if it gets validated on the client side, because it reduces number of round trips between client and server. But for the down level browsers (IE 4.0 and below and Netscape 5.0 and below) it has to be on server side. Reason being the validation code requires some scripting on client side.

4. What does the "EnableViewState" property do? Why would I want it on or off?
EnableViewState stores the current state of the page and the objects in it like text boxes, buttons, tables etc. So this helps not losing the state between the round trips between client and server. But this is a very expensive on browser. It delays rendering on the browser, so you should enable it only for the important fields/objects

5. What is the difference between Server.Transfer and Response.Redirect? Why
would I choose one over the other?
Server.Transfer transfers the currnet context of the page to the next page and also avoids double roundtrips. Where as Response.Redirect could only pass querystring and also requires roundtrip.

6. Can you give an example of when it would be appropriate to use a
web service as opposed to a non-serviced .NET component
Webservice is one of main component in Service Oriented Architecture. You could use webservices when your clients and servers are running on different networks and also different platforms. This provides a loosely coupled system. And also if the client is behind the firewall it would be easy to use webserivce since it runs on port 80 (by default) instead of having some thing else in SOA apps

7. Let's say I have an existing application written using Visual
Studio 6 (VB 6, InterDev 6) and this application utilizes Windows 2000
COM+ transaction services. How would you approach migrating this
application to .NET
You have to use System.EnterpriseServices namespace and also COMInterop the existing application

8. Can you explain the difference between an ADO.NET Dataset and an
ADO Recordset?
ADO.NET DataSet is a mini RDBMS based on XML, where as RecordSet is collection of rows. DataSet is independent of connection and communicates to the database through DataAdapter, so it could be attached to any well defined collections like hashtable, dictionary, tables, arraylists etc. practically. And also it can be bound to DataGrid etc. controls straightaway. RecordSet on the otherhand is tightly coupled to Database System.

9. Can you give an example of what might be best suited to place in
the Application_Start and Session_Start subroutines?
In the Application_Start event you could store the data, which is used throughout the life time of an application for example application name, where as Session_Start could be used to store the information, which is required for that session of the application say for example user id or user name.

10. 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.
in the above one instead of mode="InProc", you specifiy stateserver or sqlserver.


11. What are ASP.NET Web Forms? How is this technology different than
what is available though ASP (1.0-3.0)?
ASP.NET webforms are analogous to Windows Forms which are available to most VB developers. A webform is essentially a core container in a Page. An empty webform is nothing but a HTML Form tag(control) running at server and posting form to itself by default, but you could change it to post it to something else. This is a container, and you could place the web controls, user controls and HTML Controls in that one and interact with user on a postback basis.

12. How does VB.NET/C# achieve polymorphism?
Polymorphism is achieved through virtual, overloaded, overridden methods in C# and VB.NET
11. Can you explain what inheritance is and an example of when you
might use it?

13. How would you implement inheYou missed the number sequence here). Inheritance is extending the properites, behaviour, methods to child classes from super classes. VB.NET and C# provide single inheritance, means the subclasses can be derived from only one parent unlike C++, where true multiple inheritance is possible. As an alternate to implement multiple inheritance, we could do the same to implement interfaces to the parent classes and implement the same interfaces to derive the child classesritance using VB.NET/C#?

14. Whats an assembly
An assembly is the primary building block of .NET. It's a reusable, self-describing,
versionable deployment unit for types and resources. They are self-describing so to allow the .NET runtime to fully understand the application and enforce dependency and versioning rules

15. Describe the difference between inline and code behind - which is
best in a loosely coupled solution
Inline style is mixing the server side code and client side code (HTML and javascript) on the same page and run it. Where as codebehind is seperating the server side in a different page (enabling developers/coders to work) and leaving the client side code to do the presentation only (so designers would work on it). Inline code would be simplest way of approach because it doesn't require any pre-compilation. But it is not good in many ways, i. You mix the presentation and server side code together so whenever there is a change it would be tough to maintain. ii. The event processing would be a night mare in inline code. iii. Since the codebehind needs to be compile in advance, it would be faster unline inline, which is interpreted per call basis. In a loosely couple situation, code-behind would be the best way to approach. Because it provides better performance.

17. Explain what a diffgram is, and a good use for one
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sqlxml3/htm/dotnet_11pr.asp

-----------------------------------------------------------------------------------------------
more questions added....
----------
18. Describe session handling in a webform, how does it work and what
are the its limits

Sometimes it is necessary to carry a particular session data across pages.
And HTTP is a stateless protocol. In order to maintain state between
page calls, we could use cookies, hidden form fields etc. One of them is
using sessions. each sessions are maintain a unique key on the server and
serialize the data on it. Actually it is a hashtable and stores data on key/value
pair of combination. You could set a session using Session Object and retrieve the same data/state
by passing the key.
//Set
Session["abc"] = "Session Value";
// Get
string abc = Session["abc"].ToString();
The downside of sessions is scalability. Say your application gets more and more hits
and you though instead of one webserver handling it, have it in a webfarm (multiple web
servers working under one domain). You cannot transfer the session so easily across multiple
webservers. Reason is like I said, it physically serializes the state data to webserver hard disk.
.NET proposes a new way to handle this using a stateserver (actually a trimmed down sql server)
storing the web session data in a factory configured database schema or using Database with your own
schema defined to handle the sessions.


19. How would you get ASP.NET running in Apache web servers - why
would you even do this?

You need to create a CLRHost, which hosts the CLR (ASP.NET) on top of Apache.
Since Apache is #1 webserver used by many companies, this would allow more number of web site owners
to take advantage of ASP.NET and its richness.

20. Whats MSIL, and why should my developers need an appreciation of
it if at all?

MSIL is Microsoft Intermediate (Intermediary) Language. It is Microsoft's implementation of CIL (standard recognized
by ECMA and ISO) as part of CLI and C# Standardization.

.NET supports more than 21 language (I think 24 now). They compile to IL first and then this IL would get JITted to Native
code at runtime. Learning IL is advantageous in many terms. The important one is sometimes you need to optimize your
code, so you could disassemble your compile assembly using ILDASM and tweak your code and re assemble it using ILASM.


21. In what order do the events of an ASPX page execute. As a
developer is it important to undertsand these events?

This is the order of Page events
i. Page_Init
ii.Page_LoadViewState
iii. Page_LoadPostData
iv. Page_Load
v. Page_RaisePostDataChanged
vi. Page_RaisePostBackEvent
vii. Page_PreRender
viii. Page_SaveViewState
ix. Page_Render
x. Page_Dispose
xii. Page_Error (this is caused whenever there is an exception at the page level).

Out of all the Page_Load is the one where your code gets loaded and your magic should be written. page_init
occurs only once, i.e. when the page is initially created.

As a developer you need to know these, becuase your development activity is coding for these only.

22. Which method do you invoke on the DataAdapter control to load your
generated dataset with data?

Fill()

23. Can you edit data in the Repeater control?
No. Only DataList and DataGrid provide you editing capabilities.

24. Which template must you provide, in order to display data in a
Repeater control?
ItemTemplate

25. How can you provide an alternating color scheme in a Repeater
control?

Use AlternatingItemTemplate

26. 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?

The text property and the DataBind Method.

27. What base class do all Web Forms inherit from?

System.Web.UI.Page

28. What method do you use to explicitly kill a user s session?

Session.Abandon

29. How do you turn off cookies for one page in your site?
Actually I never did this. But there should be a way to do this. May be need to
write your own code to do this using Response.Cookies collection and HTTPCookie class and also SessionStateMode. Or there may be some simple way to do it. Need to do further research on this.

30. Which two properties are on every validation control?

The common properties are:
i. IsValid (bool)
ii. ControlToValidate (string)
iii. ErrorMessage (string)
iv. ValidationDisplay (Display)
v. Text (string)
The common method is:
Validate()

31. What tags do you need to add within the asp:datagrid tags to bind
columns manually?

You need to set AutoGenerateColumns Property to false.

32. How do you create a permanent cookie?

If you are developing web services and the cookies need to be travelled across multiple requests, then
you need to have permanent or persistant cookie.
In order to do this, you have to set the your webserivce CookieContainer to a newly created CookieContainer, and the
its cookie to a session value and then store the cookie(s) into the Service CookieCollection from that cookie container
if something is there othere wise add cookie to the container.

33. What tag do you use to add a hyperlink column to the DataGrid?
HyperLinkColumn

34. What is the standard you use to wrap up a call to a Web service
SOAP.

35. Which method do you use to redirect the user to another page
without performing a round trip to the client?
Server.Transfer
Response.Redirect also does that but it requires round trip between client and server.

36. What is the transport protocol you use to call a Web service SOAP
SOAP

37. True or False: A Web service can only be written in .NET
False.

38. What does WSDL stand for?
Web Services Description Language.

39. What property do you have to set to tell the grid which page to go
to when using the Pager object?
CurrentPageIndex. You need to set this one with the DataGridPageChangedEventArgs' NewPageIndex.

40. Where on the Internet would you look for Web services?
UDDI.org, UDDI.Org (even microsoft maintains a uddi server-- http://uddi.microsoft.com)
UDDI is Universal Description, Discovery and Integration of Web Services.
The UDDI servers serves as yellow pages to WebServices (visit http://www.uddi.org)


41. What tags do you need to add within the asp:datagrid tags to bind
columns manually.

Set AutoGenerateColumns Property to false on the datagrid tag

42. Which property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?

ListItem.

43. How is a property designated as read-only?
If it has only get accessor.

ex:
public class abc
{
private string stringIt="This is the string";
public string StringIt
{
get
{
return stringIt;
}
}
}

But you could set an attribute prior to the property name with [ReadOnly="true"],
if that property defined an attribute

44. Which control would you use if you needed to make sure the values
in two different controls matched?

Use CompareValidator

45. True or False: To test a Web service you must create a windows
application or Web application to consume this service?

False. The webservice comes with a test page and it provides HTTP-GET method to test.
And if the web service turned off HTTP-GET for security purposes then you need to create
a web application or windows app as a client to this to test.

46. How many classes can a single .NET DLL contain?
many is correct. Yes an assembly can contain one or more classes and an assembly can
be contained in one dll or could spread across multiple dlls. too. Take System.dll, it is collections of so many classes.
------------------------------------------------
------------more---------------------
1.1 What is .NET?
.NET is a general-purpose software development platform, similar to Java. At its core is a virtual machine that turns intermediate language (IL) into machine code. High-level language compilers for C#, VB.NET and C++ are provided to turn source code into IL. C# is a new programming language, very similar to Java. An extensive class library is included, featuring all the functionality one might expect from a contempory development platform - windows GUI development (Windows Forms), database access (ADO.NET), web development (ASP.NET), web services, XML etc.
See also Microsoft's definition.

1.2 When was .NET announced?
Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the .NET 'vision'. The July 2000 PDC had a number of sessions on .NET technology, and delegates were given CDs containing a pre-release version of the .NET framework/SDK and Visual Studio.NET.

1.3 What versions of .NET are there?
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.
.NET 1.1 was released in April 2003 - it's mostly bug fixes for 1.0.
.NET 2.0 is expected in 2005.

1.4 What operating systems does the .NET Framework run on?
The runtime supports Windows Server 2003, 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 XP and Windows 2000/2003. 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 .NET Compact Framework is a version of the .NET Framework for mobile devices, running Windows CE or Windows Mobile.
The Mono project has a version of the .NET Framework that runs on Linux.

1.5 What tools can I use to develop .NET applications?
There are a number of tools, described here in ascending order of cost:
• The .NET Framework 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 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 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.
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

1.6 Why did they call it .NET?
I don't know what they were thinking. They certainly weren't thinking of people using search tools. It's meaningless marketing nonsense - best not to think about it.

2. Terminology

2.1 What is the CLI? Is it the same as the CLR?
The CLI (Common Language Infrastructure) is the definiton of the fundamentals of the .NET framework - the Common Type System (CTS), metadata, the Virtual Execution Environment (VES) and its use of intermediate language (IL), and the support of multiple programming languages via the Common Language Specification (CLS). The CLI is documented through ECMA - see http://msdn.microsoft.com/net/ecma/ for more details.
The CLR (Common Language Runtime) is Microsoft's primary implementation of the CLI. Microsoft also have a shared source implementation known as ROTOR, for educational purposes, as well as the .NET Compact Framework for mobile devices. Non-Microsoft CLI implementations include Mono and DotGNU Portable.NET.

2.2 What is the CTS, and how does it relate to the CLS?
CTS = Common Type System. This is the full range of types that the .NET runtime understands. Not all .NET languages support all the types in the CTS.
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. This interop is very fine-grained - for example a VB.NET class can inherit from a C# class.

2.3 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 during development. The IL is then converted to machine code at the point where the software is installed, or (more commonly) at run-time by a Just-In-Time (JIT) compiler.

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

2.5 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.
Managed data: This is data that is allocated and freed by the .NET runtime's garbage collector.
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.

2.6 What is reflection?
All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.
Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

3. Assemblies

3.1 What is an assembly?
An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry point) or a library. An assembly consists of one or more files (dlls, exes, html files etc), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.
An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET runtime sees these as two completely different types. Furthermore, don't get confused between assemblies and namespaces - namespaces are merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime.
Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at the assembly boundary.
Finally, assemblies are the unit of versioning in .NET - more on this below.
3.2 How can I produce an assembly?
The simplest way to produce an assembly is directly from a .NET compiler. For example, the following C# program:
public class CTest
{
public CTest() { System.Console.WriteLine( "Hello from CTest" ); }
}
can be compiled into a library assembly (dll) like this:
csc /t:library ctest.cs
You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET SDK.
Alternatively you can compile your source into modules, and then combine the modules into an assembly using the assembly linker (al.exe). For the C# compiler, the /target:module switch is used to generate a module instead of an assembly.

3.3 What is the difference between a private assembly and a shared assembly?
• Location and visibility: A private assembly is normally used by a single application, and is stored in the application's directory, or a sub-directory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. the .NET framework classes.
• Versioning: The runtime enforces versioning constraints only on shared assemblies, not on private assemblies.

3.4 How do assemblies find each other?
By searching directory paths. There are several factors which can affect the path (such as the AppDomain host, and application configuration files), but for private assemblies the search path is normally the application's directory and its sub-directories. For shared assemblies, the search path is normally same as the private assembly path plus the shared assembly cache.

3.5 How does assembly versioning work?
Each assembly has a version number called the compatibility version. Also each reference to an assembly (from another assembly) includes both the name and version of the referenced assembly.
The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with either of the first two parts different are normally viewed as incompatible. If the first two parts are the same, but the third is different, the assemblies are deemed as 'maybe compatible'. If only the fourth part is different, the assemblies are deemed compatible. However, this is just the default guideline - it is the version policy that decides to what extent these rules are enforced. The version policy can be specified via the application configuration file.
Remember: versioning is only applied to shared assemblies, not private assemblies.

3.6 How can I develop an application that automatically updates itself from the web?
For .NET 1.x, use the Updater Application Block. For .NET 2.x, use ClickOnce.

4. Application Domains

4.1 What is an application domain?
An AppDomain can be thought of as a lightweight process. Multiple AppDomains can exist inside a Win32 process. The primary purpose of the AppDomain is to isolate applications from each other, and so it is particularly useful in hosting scenarios such as ASP.NET. An AppDomain can be destroyed by the host without affecting other AppDomains in the process.
Win32 processes provide isolation by having distinct memory address spaces. This is effective, but expensive. 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.
One non-obvious use of AppDomains is for unloading types. Currently the only way to unload a .NET type is to destroy the AppDomain it is loaded into. This is particularly useful if you create and destroy types on-the-fly via reflection.
Microsoft have an AppDomain FAQ.

4.2 How does an AppDomain get created?
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application.
AppDomains can also be explicitly created by .NET applications. Here is a C# sample which creates an AppDomain, creates an instance of an object inside it, and then executes one of the object's methods:
using System;
using System.Runtime.Remoting;
using System.Reflection;

public class CAppDomainInfo : MarshalByRefObject
{
public string GetName() { return AppDomain.CurrentDomain.FriendlyName; }
}

public class App
{
public static int Main()
{
AppDomain ad = AppDomain.CreateDomain( "Andy's new domain" );
CAppDomainInfo adInfo = (CAppDomainInfo)ad.CreateInstanceAndUnwrap(
Assembly.GetCallingAssembly().GetName().Name, "CAppDomainInfo" );
Console.WriteLine( "Created AppDomain name = " + adInfo.GetName() );
return 0;
}
}

4.3 Can I write my own .NET host?
Yes. For an example of how to do this, take a look at the source for the dm.net moniker developed by Jason Whittington and Don Box. There is also a code sample in the .NET SDK called CorHost.

5. Garbage Collection
5.1 What is garbage collection?
Garbage collection is a heap-management strategy where a run-time component takes responsibility for managing the lifetime of the memory used by objects. This concept is not new to .NET - Java and many other languages/runtimes have used garbage collection for some time.

5.2 Is it true that objects don't always get destroyed immediately when the last reference goes away?
Yes. The garbage collector offers no guarantees about the time when an object will be destroyed and its memory reclaimed.
There was an interesting thread on the DOTNET list, started by Chris Sells, about the implications of non-deterministic destruction of objects in C#. In October 2000, Microsoft's Brian Harry posted a lengthy analysis of the problem. Chris Sells' response to Brian's posting is here.

5.3 Why doesn't the .NET runtime offer deterministic destruction?
Because of the garbage collection algorithm. The .NET garbage collector works by periodically running through a list of all the objects that are currently being referenced by an application. All the objects that it doesn't find during this search are ready to be destroyed and the memory reclaimed. The implication of this algorithm is that the runtime doesn't get notified immediately when the final reference on an object goes away - it only finds out during the next 'sweep' of the heap.
Futhermore, this type of algorithm works best by performing the garbage collection sweep as rarely as possible. Normally heap exhaustion is the trigger for a collection sweep.

5.4 Is the lack of deterministic destruction in .NET a problem?
It's certainly an issue that affects component design. If you have objects that maintain expensive or scarce resources (e.g. database locks), you need to provide some way 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 ownership-management mechanism is needed to handle distributed objects - unfortunately the runtime offers no help with this.

5.5 Should I implement Finalize on my class? Should I implement IDisposable?
This issue is a little more complex than it first appears. There are really two categories of class that require deterministic destruction - the first category manipulate unmanaged types directly, whereas the second category manipulate managed types that require deterministic destruction. An example of the first category is a class with an IntPtr member representing an OS file handle. An example of the second category is a class with a System.IO.FileStream member.
For the first category, it makes sense to implement IDisposable and override Finalize. This allows the object user to 'do the right thing' by calling Dispose, but also provides a fallback of freeing the unmanaged resource in the Finalizer, should the calling code fail in its duty. However this logic does not apply to the second category of class, with only managed resources. In this case implementing Finalize is pointless, as managed member objects cannot be accessed in the Finalizer. This is because there is no guarantee about the ordering of Finalizer execution. So only the Dispose method should be implemented. (If you think about it, it doesn't really make sense to call Dispose on member objects from a Finalizer anyway, as the member object's Finalizer will do the required cleanup.)
For classes that need to implement IDisposable and override Finalize, see Microsoft's documented pattern.
Note that some developers argue that implementing a Finalizer is always a bad idea, as it hides a bug in your code (i.e. the lack of a Dispose call). A less radical approach is to implement Finalize but include a Debug.Assert at the start, thus signalling the problem in developer builds but allowing the cleanup to occur in release builds.

5.6 Do I have any control over the garbage collection algorithm?
A little. For example the System.GC class exposes a Collect method, which forces the garbage collector to collect all unreferenced objects immediately.
Also there is a gcConcurrent setting that can be specified via the application configuration file. This specifies whether or not the garbage collector performs some of its collection activities on a separate thread. The setting only applies on multi-processor machines, and defaults to true.

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

5.8 What is the lapsed listener problem?
The lapsed listener problem is one of the primary causes of leaks in .NET applications. It occurs when a subscriber (or 'listener') signs up for a publisher's event, but fails to unsubscribe. The failure to unsubscribe means that the publisher maintains a reference to the subscriber as long as the publisher is alive. For some publishers, this may be the duration of the application.
This situation causes two problems. The obvious problem is the leakage of the subscriber object. The other problem is the performance degredation due to the publisher sending redundant notifications to 'zombie' subscribers.
There are at least a couple of solutions to the problem. The simplest is to make sure the subscriber is unsubscribed from the publisher, typically by adding an Unsubscribe() method to the subscriber. Another solution, documented here by Shawn Van Ness, is to change the publisher to use weak references in its subscriber list.

5.9 When do I need to use GC.KeepAlive?
It's very unintuitive, but the runtime can decide that an object is garbage much sooner than you expect. More specifically, an object can become garbage while a method is executing on the object, which is contrary to most developers' expectations. Chris Brumme explains the issue on his blog. I've taken Chris's code and expanded it into a full app that you can play with if you want to prove to yourself that this is a real problem:
using System;
using System.Runtime.InteropServices;

class Win32
{
[DllImport("kernel32.dll")]
public static extern IntPtr CreateEvent( IntPtr lpEventAttributes,
bool bManualReset,bool bInitialState, string lpName);

[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool CloseHandle(IntPtr hObject);

[DllImport("kernel32.dll")]
public static extern bool SetEvent(IntPtr hEvent);
}

class EventUser
{
public EventUser()
{
hEvent = Win32.CreateEvent( IntPtr.Zero, false, false, null );
}

~EventUser()
{
Win32.CloseHandle( hEvent );
Console.WriteLine("EventUser finalized");
}

public void UseEvent()
{
UseEventInStatic( this.hEvent );
}

static void UseEventInStatic( IntPtr hEvent )
{
//GC.Collect();
bool bSuccess = Win32.SetEvent( hEvent );
Console.WriteLine( "SetEvent " + (bSuccess ? "succeeded" : "FAILED!") );
}

IntPtr hEvent;
}

class App
{
static void Main(string[] args)
{
EventUser eventUser = new EventUser();
eventUser.UseEvent();
}
}
If you run this code, it'll probably work fine, and you'll get the following output:
SetEvent succeeded
EventDemo finalized
However, if you uncomment the GC.Collect() call in the UseEventInStatic() method, you'll get this output:
EventDemo finalized
SetEvent FAILED!
(Note that you need to use a release build to reproduce this problem.)
So what's happening here? Well, at the point where UseEvent() calls UseEventInStatic(), a copy is taken of the hEvent field, and there are no further references to the EventUser object anywhere in the code. So as far as the runtime is concerned, the EventUser object is garbage and can be collected. Normally of course the collection won't happen immediately, so you'll get away with it, but sooner or later a collection will occur at the wrong time, and your app will fail.
A solution to this problem is to add a call to GC.KeepAlive(this) to the end of the UseEvent method, as Chris explains.

6. Serialization
6.1 What is serialization?
Serialization is the process of converting an object into a stream of bytes. Deserialization is the opposite process, i.e. 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).

6.2 Does the .NET Framework have in-built support for serialization?
There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

6.3 I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or BinaryFormatter?
It depends. XmlSerializer has severe limitations such as the requirement that the target class has a parameterless constructor, and only public read/write properties and fields can be serialized. However, on the plus side, XmlSerializer has good support for customising the XML document that is produced or consumed. XmlSerializer's features mean that it is most suitable for cross-platform work, or for constructing objects from existing XML documents.
SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer. They can serialize private fields, for example. However they both require that the target class be marked with the [Serializable] attribute, so like XmlSerializer the class needs to be written with serialization in mind. Also there are some quirks to watch out for - for example on deserialization the constructor of the new object is not invoked.
The choice between SoapFormatter and BinaryFormatter depends on the application. BinaryFormatter makes sense where both serialization and deserialization will be performed on the .NET platform and where performance is important. SoapFormatter generally makes more sense in all other cases, for ease of debugging if nothing else.

6.4 Can I customise the serialization process?
Yes. XmlSerializer supports a range of attributes that can be used to configure serialization for a particular class. For example, a field or property can be marked with the [XmlIgnore] attribute to exclude it from serialization. Another example is the [XmlElement] attribute, which can be used to specify the XML element name to be used for a particular property or field.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some extent by attributes. For example, the [NonSerialized] attribute is the equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the serialization process can be acheived by implementing the the ISerializable interface on the class whose instances are to be serialized.

6.5 Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first time you serialize or deserialize an object of a given type in an application, there is a significant delay. This normally doesn't matter, but it may mean, for example, that XmlSerializer is a poor choice for loading configuration settings during startup of a GUI application.

6.6 Why do I get errors when I try to serialize a Hashtable?
XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

6.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is?
Look at the InnerException property of the exception that is thrown to get a more specific error message.

6.8 Why am I getting an InvalidOperationException when I serialize an ArrayList?
XmlSerializer needs to know in advance what type of objects it will find in an ArrayList. To specify the type, use the XmlArrayItem attibute like this:
public class Person
{
public string Name;
public int Age;
}

public class Population
{
[XmlArrayItem(typeof(Person))] public ArrayList People;
}

7. Attributes

7.1 What are attributes?
There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be attached to a class and means that instances of the class can be serialized.
[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 have encountered Keith Brown's universal delegator you'll be familiar with this idea.

7.2 Can I create my own metadata attributes?
Yes. Simply derive a class from System.Attribute and mark it with the AttributeUsage attribute. For example:
[AttributeUsage(AttributeTargets.Class)]
public class InspiredByAttribute : System.Attribute
{
public string InspiredBy;

public InspiredByAttribute( string inspiredBy )
{
InspiredBy = inspiredBy;
}
}


[InspiredBy("Andy Mc's brilliant .NET FAQ")]
class CTest
{
}


class CApp
{
public static void Main()
{
object[] atts = typeof(CTest).GetCustomAttributes(true);

foreach( object att in atts )
if( att is InspiredByAttribute )
Console.WriteLine( "Class CTest was inspired by {0}", ((InspiredByAttribute)att).InspiredBy );
}
}

7.3 Can I create my own context attibutes?
Yes. Take a look at Peter Drayton's Tracehook.NET.

8. Code Access Security

8.1 What is Code Access Security (CAS)?
CAS is the part of the .NET security model that determines whether or not code is allowed to run, and what resources it can use when it is running. For example, it is CAS that will prevent a .NET web applet from formatting your hard disk.

8.2 How does CAS work?
The CAS security policy revolves around two key concepts - code groups and permissions. Each .NET assembly is a member of a particular code group, and each code group is granted the permissions specified in a named permission set.
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.)


9. Intermediate Language (IL)
9.1 Can I look at the IL for an assembly?
Yes. MS supply a tool called Ildasm that can be used to view the metadata and IL for an assembly.

9.2 Can source code be reverse-engineered from IL?
Yes, it is often relatively straightforward to regenerate high-level source from IL. Lutz Roeder's Reflector does a very good job of turning IL into C# or VB.NET.

9.3 How can I stop my code being reverse-engineered from IL?
You can buy an IL obfuscation tool. These tools work by 'optimising' the IL in such a way that reverse-engineering becomes much more difficult.
Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL.

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

9.5 Can I do things in IL that I can't do in C#?
Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays.

10. Implications for COM
10.1 Does .NET replace COM?
This subject causes a lot of controversy, as you'll see if you read the mailing list archives. Take a look at the following two threads:
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&D=0&P=68241
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R60761
The bottom line is that .NET has its own mechanisms for type interaction, and they don't use COM. No IUnknown, no IDL, no typelibs, no registry-based activation. This is mostly good, as a lot of COM was ugly. Generally speaking, .NET allows you to package and use components in a similar way to COM, but makes the whole thing a bit easier.

10.2 Is DCOM dead?
Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on DCOM. DCOM was pretty much dead anyway, once firewalls became widespread and Microsoft got SOAP fever. Of course DCOM will still be used in interop scenarios.

10.3 Is COM+ dead?
Not immediately. The approach for .NET 1.0 was 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 were provided to make this as painless as possible. Over time it is expected that interop will become more seamless - this may mean that some services become a core part of the CLR, and/or it may mean that some services will be rewritten as managed code which runs on top of the CLR.
For more on this topic, search for postings by Joe Long in the archives - Joe is the MS group manager for COM+. Start with this message:
http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R68370

10.4 Can I use COM components from .NET programs?
Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to .NET-compatible types.
Here's a simple example for those familiar with ATL. First, create an ATL component which implements the following IDL:
import "oaidl.idl";
import "ocidl.idl";

[
object,
uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206),
helpstring("ICppName Interface"),
pointer_default(unique),
oleautomation
]

interface ICppName : IUnknown
{
[helpstring("method SetName")] HRESULT SetName([in] BSTR name);
[helpstring("method GetName")] HRESULT GetName([out,retval] BSTR *pName );
};

[
uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D),
version(1.0),
helpstring("cppcomserver 1.0 Type Library")
]
library CPPCOMSERVERLib
{
importlib("stdole32.tlb");
importlib("stdole2.tlb");
[
uuid(600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70),
helpstring("CppName Class")
]
coclass CppName
{
[default] interface ICppName;
};
};
When you've built the component, you should get a typelibrary. Run the TLBIMP utility on the typelibary, like this:
tlbimp cppcomserver.tlb
If successful, you will get a message like this:
Typelib imported successfully to CPPCOMSERVERLib.dll
You now need a .NET client - let's use C#. Create a .cs file containing the following code:
using System;
using CPPCOMSERVERLib;

public class MainApp
{
static public void Main()
{
CppName cppname = new CppName();
cppname.SetName( "bob" );
Console.WriteLine( "Name is " + cppname.GetName() );
}
}
Compile the C# code like this:
csc /r:cppcomserverlib.dll csharpcomclient.cs
Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using TLBIMP. You should now be able to run csharpcomclient.exe, and get the following output on the console:
Name is bob

10.5 Can I use .NET components from COM programs?
Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW (see previous question), but works in the opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW can be developed. Also, for COM to 'see' the .NET component, the .NET component must be registered in the registry.
Here's a simple example. Create a C# file called testcomserver.cs and put the following in it:
using System;
using System.Runtime.InteropServices;

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.

10.6 Is ATL redundant in the .NET world?
Yes. ATL will continue to be valuable for writing COM components for some time, but it has no place in the .NET world.

11. Miscellaneous
11.1 How does .NET remoting work?
.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet).
Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format.
There are a number of styles of remote access:
• SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished.
• Singleton. All incoming requests from clients are processed by a single server object.
• Client-activated object. This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it.
Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure. Objects have a default renew time - the lease is renewed when a successful call is made from the client to the object. The client can also explicitly renew the lease.
If you're interested in using XML-RPC as an alternative to SOAP, take a look at Charles Cook's XML-RPC.Net.

11.2 How can I get at the Win32 API from a .NET program?
Use P/Invoke. This uses similar technology to COM Interop, but is used to access static DLL entry points instead of COM objects. Here is an example of C# calling the Win32 MessageBox function:
using System;
using System.Runtime.InteropServices;

class MainApp
{
[DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true, CharSet=CharSet.Auto)]
public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType);

public static void Main()
{
MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 );
}
}
Pinvoke.net is a great resource for off-the-shelf P/Invoke signatures.

11.3 How do I write to the application configuration file at runtime?
You don't. See http://www.interact-sw.co.uk/iangblog/2004/11/25/savingconfig.

11.4 What is the difference between an event and a delegate?
An event is just a wrapper for a multicast delegate. Adding a public event to a class is almost the same as adding a public multicast delegate field. In both cases, subscriber objects can register for notifications, and in both cases the publisher object can send notifications to the subscribers. However, a public multicast delegate has the undesirable property that external objects can invoke the delegate, something we'd normally want to restrict to the publisher. Hence events - an event adds public methods to the containing class to add and remove receivers, but does not make the invocation mechanism public.
See this post by Julien Couvreur for more discussion.

11.5 What size is a .NET object?
Each instance of a reference type has two fields maintained by the runtime - a method table pointer and a sync block. These are 4 bytes each on a 32-bit system, making a total of 8 bytes per object overhead. Obviously the instance data for the type must be added to this to get the overall size of the object. So, for example, instances of the following class are 12 bytes each:
class MyInt
{
...
private int x;
}
However, note that with the current implementation of the CLR there seems to be a minimum object size of 12 bytes, even for classes with no data (e.g. System.Object).
Values types have no equivalent overhead.

12. .NET 2.0
12.1 What are the new features of .NET 2.0?
Generics, anonymous methods, partial classes, iterators, property visibility (separate visibility for get and set) and static classes. See http://msdn.microsoft.com/msdnmag/issues/04/05/C20/default.aspx for more information about these features.

12.2 What are the new 2.0 features useful for?
Generics are useful for writing efficient type-independent code, particularly where the types might include value types. The obvious application is container classes, and the .NET 2.0 class library includes a suite of generic container classes in the System.Collections.Generic namespace. Here's a simple example of a generic container class being used:
List myList = new List();
myList.Add( 10 );
Anonymous methods reduce the amount of code you have to write when using delegates, and are therefore especially useful for GUI programming. Here's an example
AppDomain.CurrentDomain.ProcessExit += delegate { Console.WriteLine("Process ending ..."); };
Partial classes is a useful feature for separating machine-generated code from hand-written code in the same class, and will therefore be heavily used by development tools such as Visual Studio.
Iterators reduce the amount of code you need to write to implement IEnumerable/IEnumerator. Here's some sample code:
static void Main()
{
RandomEnumerator re = new RandomEnumerator( 5 );
foreach( double r in re )
Console.WriteLine( r );
Console.Read();
}

class RandomEnumerator : IEnumerable
{
public RandomEnumerator(int size) { m_size = size; }

public IEnumerator GetEnumerator()
{
Random rand = new Random();
for( int i=0; i < m_size =" 0;">
{
public static void Dispose(T obj) { obj.Dispose(); }
}
The C# compiler will refuse to compile this code, as the type T has not been constrained, and therefore only supports the methods of System.Object. Dispose is not a method on System.Object, so the compilation fails. To fix this code, we need to add a where clause, to reassure the compiler that our type T does indeed have a Dispose method
static class Disposer where T : IDisposable
{
public static void Dispose(T obj) { obj.Dispose(); }
}
The problem is that the requirement for explicit contraints is very limiting. We can use constraints to say that T implements a particular interface, but we can't dilute that to simply say that T implements a particular method. Contrast this with C++ templates (for example), where no constraint at all is required - it is assumed (and verified at compile time) that if the code invokes the Dispose() method on a type, then the type will support the method.
In fact, after writing generic code with interface constraints, we quickly see that we haven't gained much over non-generic interface-based programming. For example, we can easily rewrite the Disposer class without generics:
static class Disposer
{
public static void Dispose( IDisposable obj ) { obj.Dispose(); }
}
For more on this topic, start by reading the following articles:
Bruce Eckel: http://www.mindview.net/WebLog/log-0050
Ian Griffiths: http://www.interact-sw.co.uk/iangblog/2004/03/14/generics
Charles Cook: http://www.cookcomputing.com/blog/archives/000425.html
Brad Wilson: http://dotnetguy.techieswithcats.com/archives/004273.shtml

12.4 What's new in the .NET 2.0 class library?
Here is a selection of new features in the .NET 2.0 class library (beta 1):
• Generic collections in the System.Collections.Generic namespace.
• The System.Nullable type. (Note that C# has special syntax for this type, e.g. int? is equivalent to Nullable)
• The GZipStream and DeflateStream classes in the System.IO.Compression namespace.
• The Semaphore class in the System.Threading namespace.
• Wrappers for DPAPI in the form of the ProtectedData and ProtectedMemory classes in the System.Security.Cryptography namespace.
• The IPC remoting channel in the System.Runtime.Remoting.Channels.Ipc namespace, for optimised intra-machine communication.

13. Class Library
13.1 Threads
13.1.1 How do I spawn a thread?
Create an instance of a System.Threading.Thread object, passing it an instance of a ThreadStart delegate that will be executed on the new thread. For example:
class MyThread
{
public MyThread( string initData )
{
m_data = initData;
m_thread = new Thread( new ThreadStart(ThreadMain) );
m_thread.Start();
}

// ThreadMain() is executed on the new thread.
private void ThreadMain()
{
Console.WriteLine( m_data );
}

public void WaitUntilFinished()
{
m_thread.Join();
}

private Thread m_thread;
private string m_data;
}
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();

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

13.1.3 How do I use the thread pool?
By passing an instance of a WaitCallback delegate to the ThreadPool.QueueUserWorkItem() method
class CApp
{
static void Main()
{
string s = "Hello, World";
ThreadPool.QueueUserWorkItem( new WaitCallback( DoWork ), s );

Thread.Sleep( 1000 ); // Give time for work item to be executed
}

// DoWork is executed on a thread from the thread pool.
static void DoWork( object state )
{
Console.WriteLine( state );
}
}

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

13.1.5 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:
class C
{
public void f()
{
lock( m_object )
{
...
}
}

private m_object = new object();
}
Actually, it could be argued that this version of the code is superior, as the lock is totally encapsulated within the class, and not accessible to the user of the object.

13.1.6 Should I use ReaderWriterLock instead of Monitor.Enter/Exit?
Maybe, but be careful. ReaderWriterLock is used to allow multiple threads to read from a data source, while still granting exclusive access to a single writer thread. This makes sense for data access that is mostly read-only, but there are some caveats. First, ReaderWriterLock is relatively poor performing compared to Monitor.Enter/Exit, which offsets some of the benefits. Second, you need to be very sure that the data structures you are accessing fully support multithreaded read access. Finally, there is apparently a bug in the v1.1 ReaderWriterLock that can cause starvation for writers when there are a large number of readers.
Ian Griffiths has some interesting discussion on ReaderWriterLock here and here.

13.2 Tracing
13.2.1 Is there built-in support for tracing/logging?
Yes, in the System.Diagnostics namespace. There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.

13.2.2 Can I redirect tracing to a file?
Yes. The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose.
Here's how to use the TextWriterTraceListener class to redirect Trace output to a file:
Trace.Listeners.Clear();
FileStream fs = new FileStream( @"c:\log.txt", FileMode.Create, FileAccess.Write );
Trace.Listeners.Add( new TextWriterTraceListener( fs ) );

Trace.WriteLine( @"This will be writen to c:\log.txt!" );
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.

13.2.3 Can I customise the trace output?
Yes. You can write your own TraceListener-derived class, and direct all output through it. Here's a simple example, which derives from TextWriterTraceListener (and therefore has in-built support for writing to files, as shown above) and adds timing information and the thread ID for each trace line:
class MyListener : TextWriterTraceListener
{
public MyListener( Stream s ) : base(s)
{
}

public override void WriteLine( string s )
{
Writer.WriteLine( "{0:D8} [{1:D4}] {2}",
Environment.TickCount - m_startTickCount,
AppDomain.GetCurrentThreadId(),
s );
}

protected int m_startTickCount = Environment.TickCount;
}
(Note that this implementation is not complete - the TraceListener.Write method is not overridden for example.)
The beauty of this approach is that when an instance of MyListener is added to the Trace.Listeners collection, all calls to Trace.WriteLine() go through MyListener, including calls made by referenced assemblies that know nothing about the MyListener class.

13.2.4 Are there any third party logging components available?
Log4net is a port of the established log4j Java logging component.