1.1 What is C#?
C# is a programming language designed by Microsoft. It is loosely based on C/C++, and bears a striking similarity to Java. 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++.”
You can get the ECMA C# spec in PDF form here, or use Jon Jagger’s html version.

1.2 How do I develop C# apps?
The (free) .NET SDK contains the C# command-line compiler (csc.exe). Visual Studio has fully integrated support for C# development. On Linux you can use Mono.

1.3 Does C# replace C++?
There are three options open to the Windows developer from a C++ background:
• Stick with standard C++. Don’t use .NET at all.
• Use C++ with .NET. Microsoft supply a .NET C++ compiler that produces IL rather than machine code. However to make full use of the .NET environment (e.g. garbage collection), a set of extensions are required to standard C++. In .NET 1.x this extended language is called Managed Extensions for C++. In .NET 2.0 ME C++ has been completely redesigned under the stewardship of Stan Lippman, and renamed C++/CLI.
• Forget C++ and use C#.
Each of these options has merits, depending on the developer and the application. For my own part, I intend to use C# where possible, falling back to C++ only where necessary. ME C++ (soon to be C++/CLI) is very useful for interop between new .NET code and old C++ code – simply write a managed wrapper class using ME C++, then use the managed class from C#. From experience, this works well.
1.4 Does C# have its own class library?
Not exactly. The .NET Framework has a comprehensive class library, which C# can make use of. C# does not have its own class library.

2. Types
2.1 What standard types does C# use?
C# supports a very similar range of basic types to C++, including int, long, float, double, char, string, arrays, structs and classes. However, don’t assume too much. The names may be familiar, but many of the details are different. For example, a long is 64 bits in C#, whereas in C++ the size of a long depends on the platform (typically 32 bits on a 32-bit platform, 64 bits on a 64-bit platform). Also classes and structs are almost the same in C++ – this is not true for C#. Finally, chars and strings in .NET are 16-bit (Unicode/UTF-16), not 8-bit like C++.
2.2 Is it true that all C# types derive from a common base class?
Yes and no. All types can be treated as if they derive from object (System.Object), but in order to treat an instance of a value type (e.g. int, float) as object-derived, the instance must be converted to a reference type using a process called ‘boxing’. In theory a developer can forget about this and let the run-time worry about when the conversion is necessary, but in reality this implicit conversion can have side-effects that may trip up the unwary.
2.3 So I can pass an instance of a value type to a method that takes an object as a parameter?
Yes. For example:
class CApplication
{
public static void Main()
{
int x = 25;
string s = “fred”;

DisplayMe( x );
DisplayMe( s );
}

static void DisplayMe( object o )
{
System.Console.WriteLine( “You are {0}”, o );
}
}
This would display:
You are 25
You are fred
2.4 What are the fundamental differences between value types and reference types?
C# divides types into two categories – value types and reference types. Most of the intrinsic types (e.g. int, char) are value types. Structs are also value types. Reference types include classes, arrays and strings. The basic idea is straightforward – an instance of a value type represents the actual data, whereas an instance of a reference type represents a pointer or reference to the data.
The most confusing aspect of this for C++ developers is that C# has predetermined which types are represented as values, and which are represented as references. A C++ developer expects to take responsibility for this decision.
For example, in C++ we can do this:
int x1 = 3; // x1 is a value on the stack
int *x2 = new int(3) // x2 is a pointer to a value on the heap
but in C# there is no control:
int x1 = 3; // x1 is a value on the stack
int x2 = new int();
x2 = 3; // x2 is also a value on the stack!
2.5 Okay, so an int is a value type, and a class is a reference type. How can int be derived from object?
It isn’t, really. When an int is being used as an int, it is a value. However, when it is being used as an object, it is a reference to an integer value (on the managed heap). In other words, when you treat an int as an object, the runtime automatically converts the int value to an object reference. This process is called boxing. The conversion involves copying the int to the heap, and creating an object instance which refers to it. Unboxing is the reverse process – the object is converted back to a value.
int x = 3; // new int value 3 on the stack
object objx = x; // new int on heap, set to value 3 – still have x=3 on stack
int y = (int)objx; // new value 3 on stack, still got x=3 on stack and objx=3 on heap
2.6 Are C# references the same as C++ references?
Not quite. The basic idea is the same, but one significant difference is that C# references can be null . So you cannot rely on a C# reference pointing to a valid object. In that respect a C# reference is more like a C++ pointer than a C++ reference. If you try to use a null reference, a NullReferenceException is thrown.
For example, look at the following method:
void displayStringLength( string s )
{
Console.WriteLine( “String is length {0}”, s.Length );
}
The problem with this method is that it will throw a NullReferenceException if called like this:
string s = null;
displayStringLength( s );
Of course for some situations you may deem a NullReferenceException to be a perfectly acceptable outcome, but in this case it might be better to re-write the method like this:
void displayStringLength( string s )
{
if( s == null )
Console.WriteLine( “String is null” );
else
Console.WriteLine( “String is length {0}”, s.Length );
}
2.7 Can I use typedefs in C#?
No, C# has no direct equivalent of the C++ typedef. C# does allow an alias to be specified via the using keyword:
using IntList = System.Collections.Generic.List;
but the alias only applies in the file in which it is declared. A workaround in some cases is to use inheritance:
public class IntList : List { }
The pros and cons of this approach are discussed here.
3. Classes and Structs
3.1 Structs are largely redundant in C++. Why does C# have them?
In C++, a struct and a class are pretty much the same thing. The only difference is the default visibility level (public for structs, private for classes). However, in C# structs and classes are very different. In C#, structs are value types (instances stored directly on the stack, or inline within heap-based objects), whereas classes are reference types (instances stored on the heap, accessed indirectly via a reference). Also structs cannot inherit from structs or classes, though they can implement interfaces. Structs cannot have destructors. A C# struct is much more like a C struct than a C++ struct.
3.2 Does C# support multiple inheritance (MI)?
No, though it does support implementation of multiple interfaces on a single class or struct.


3.3 Is a C# interface the same as a C++ abstract class?

No, not quite. An abstract class in C++ cannot be instantiated, but it can (and often does) contain implementation code and/or data members. A C# interface cannot contain any implementation code or data members – it is simply a group of method names & signatures. A C# interface is more like a COM interface than a C++ abstract class.
3.4 Are C# constructors the same as C++ constructors?
Very similar, but there are some significant differences. First, C# supports constructor chaining. This means one constructor can call another:
class Person
{
public Person( string name, int age ) { … }
public Person( string name ) : this( name, 0 ) {}
public Person() : this( “”, 0 ) {}
}
Another difference is that virtual method calls within a constructor are routed to the most derived implementation – see Can I Call a virtual method from a constructor.
Error handling is also somewhat different. If an exception occurs during construction of a C# object, the destuctor (finalizer) will still be called. This is unlike C++ where the destructor is not called if construction is not completed. (Thanks to Jon Jagger for pointing this out.)
Finally, C# has static constructors. The static constructor for a class runs before the first instance of the class is created.
Also note that (like C++) some C# developers prefer the factory method pattern over constructors. See Brad Wilson’s article.


3.5 Are C# destructors the same as C++ destructors?

No. They look the same but they are very different. The C# destructor syntax (with the familiar ~ character) is just syntactic sugar for an override of the System.Object Finalize method. This Finalize method is called by the garbage collector when it determines that an object is no longer referenced, before it frees the memory associated with the object. So far this sounds like a C++ destructor. The difference is that the garbage collector makes no guarantees about when this procedure happens. Indeed, the algorithm employed by the CLR garbage collector means that it may be a long time after the application has finished with the object. This lack of certainty is often termed ‘non-deterministic finalization’, and it means that C# destructors are not suitable for releasing scarce resources such as database connections, file handles etc.
To achieve deterministic destruction, a class must offer a method to be used for the purpose. The standard approach is for the class to implement the IDisposable interface. The user of the object must call the Dispose() method when it has finished with the object. C# offers the ‘using’ construct to make this easier.
3.6 If C# destructors are so different to C++ destructors, why did MS use the same syntax?
Presumably they wanted C++ programmers to feel at home. I think they made a mistake.
3.7 Are all methods virtual in C#?
No. Like C++, methods are non-virtual by default, but can be marked as virtual.
3.8 How do I declare a pure virtual function in C#?
Use the abstract modifier on the method. The class must also be marked as abstract (naturally). Note that abstract methods cannot have an implementation (unlike pure virtual C++ methods).
3.9 Can I call a virtual method from a constructor/destructor?
Yes, but it’s generally not a good idea. The mechanics of object construction in .NET are quite different from C++, and this affects virtual method calls in constructors.
C++ constructs objects from base to derived, so when the base constructor is executing the object is effectively a base object, and virtual method calls are routed to the base class implementation. By contrast, in .NET the derived constructor is executed first, which means the object is always a derived object and virtual method calls are always routed to the derived implementation. (Note that the C# compiler inserts a call to the base class constructor at the start of the derived constructor, thus preserving standard OO semantics by creating the illusion that the base constructor is executed first.)
The same issue arises when calling virtual methods from C# destructors. A virtual method call in a base destructor will be routed to the derived implementation.

3.10 Should I make my destructor virtual?
A C# destructor is really just an override of the System.Object Finalize method, and so is virtual by definition.
4. Exceptions


4.1 Can I use exceptions in C#?

Yes, in fact exceptions are the recommended error-handling mechanism in C# (and in .NET in general). Most of the .NET framework classes use exceptions to signal errors.


4.2 What types of object can I throw as exceptions?

Only instances of the System.Exception classes, or classes derived from System.Exception. This is in sharp contrast with C++ where instances of almost any type can be thrown.


4.3 Can I define my own exceptions?

Yes, just derive your exception class from System.Exception.
Note that if you want your exception to cross remoting boundaries you’ll need to do some extra work – see http://www.thinktecture.com/Resources/RemotingFAQ/CustomExceptions.html for details.


4.4 Does the System.Exception class have any cool features?

Yes – the feature which stands out is the StackTrace property. This provides a call stack which records where the exception was thrown from. For example, the following code:
using System;

class CApp
{
public static void Main()
{
try
{
f();
}
catch( Exception e )
{
Console.WriteLine( “System.Exception stack trace = \n{0}”, e.StackTrace );
}
}

static void f()
{
throw new Exception( “f went pear-shaped” );
}
}
produces this output:
System.Exception stack trace =
at CApp.f()
at CApp.Main()
Note, however, that this stack trace was produced from a debug build. A release build may optimise away some of the method calls which could mean that the call stack isn’t quite what you expect.
4.5 When should I throw an exception?
This is the subject of some debate, and is partly a matter of taste. However, it is accepted by many that exceptions should be thrown only when an ‘unexpected’ error occurs. How do you decide if an error is expected or unexpected? This is a judgement call, but a straightforward example of an expected error is failing to read from a file because the seek pointer is at the end of the file, whereas an example of an unexpected error is failing to allocate memory from the heap.


4.6 Does C# have a ‘throws’ clause?

No, unlike Java, C# does not require (or even allow) the developer to specify the exceptions that a method can throw.
5. Run-time Type Information
5.1 How can I check the type of an object at runtime?
You can use the is keyword. For example:
using System;

class CApp
{
public static void Main()
{
string s = “fred”;
long i = 10;

Console.WriteLine( “{0} is {1}an integer”, s, (IsInteger(s) ? “” : “not “) );
Console.WriteLine( “{0} is {1}an integer”, i, (IsInteger(i) ? “” : “not “) );
}

static bool IsInteger( object obj )
{
if( obj is int || obj is long )
return true;
else
return false;
}
}
produces the output:
fred is not an integer
10 is an integer
5.2 Can I get the name of a type at runtime?
Yes, use the GetType method of the object class (which all types inherit from). For example:
using System;

class CTest
{
class CApp
{
public static void Main()
{
long i = 10;
CTest ctest = new CTest();

DisplayTypeInfo( ctest );
DisplayTypeInfo( i );
}

static void DisplayTypeInfo( object obj )
{
Console.WriteLine( “Type name = {0}, full type name = {1}”, obj.GetType(), obj.GetType().FullName );
}
}
}
produces the following output:
Type name = CTest, full type name = CTest
Type name = Int64, full type name = System.Int64

5.3 What is the difference between typeof and GetType()?
Apart from the obvious (i.e. typeof operates on a type whereas GetType operates on an object), the main thing to watch out for is that GetType returns the underlying type of the object, which may not be the same as the type of the reference to the object. For example:
class Base { }
class Derived : Base { }

class Program
{
static void Main()
{
ShowType( new Derived() );
}

static void ShowType( Base b )
{
Console.WriteLine(typeof(Base));
Console.WriteLine(b.GetType());
}
}
gives the following output:
Base
Derived
6. Miscellaneous
6.1 How do I do a case-insensitive string comparison?
Use the String.Compare function. Its third parameter is a boolean which specifies whether case should be ignored or not.
“fred” == “Fred” // false
System.String.Compare( “fred”, “Fred”, true ) == 0 // true
For more control over the comparison, e.g. exotic features like width-sensitivity, consider using System.Globalization.CompareInfo.Compare(), e.g.
CultureInfo.CurrentCulture.CompareInfo.Compare(
“fred”, “Fred”,
CompareOptions.IgnoreCase |
CompareOptions.IgnoreKanaType |
CompareOptions.IgnoreWidth
);

6.2 Does C# support a variable number of arguments?
Yes, using the params keyword. The arguments are specified as a list of arguments of a specific type, e.g. int. For ultimate flexibility, the type can be object. The standard example of a method which uses this approach is System.Console.WriteLine().
6.3 How can I process command-line arguments?
Like this:
using System;

class CApp
{
public static void Main( string[] args )
{
Console.WriteLine( “You passed the following arguments:” );
foreach( string arg in args )
Console.WriteLine( arg );
}
}
6.4 Does C# do array bounds checking?
Yes. An IndexOutOfRange exception is used to signal an error.
6.5 How can I make sure my C# classes will interoperate with other .NET languages?
Make sure your C# code conforms to the Common Language Subset (CLS). To help with this, add the [assembly:CLSCompliant(true)] global attribute to your C# source files. The compiler will emit an error if you use a C# feature which is not CLS-compliant.
6.6 How do I use the ‘using’ keyword with multiple objects?
You can nest using statements, like this:
using( obj1 )
{
using( obj2 )
{

}
}
However consider using this more aesthetically pleasing (but functionally identical) formatting:
using( obj1 )
using( obj2 )
{

}
6.7 What is the difference between == and object.Equals?
For value types, == and Equals() usually compare two objects by value. For example:
int x = 10;
int y = 10;
Console.WriteLine( x == y );
Console.WriteLine( x.Equals(y) );
will display:
True
True
However things are more complex for reference types. Generally speaking, for reference types == is expected to perform an identity comparison, i.e. it will only return true if both references point to the same object. By contrast, Equals() is expected to perform a value comparison, i.e. it will return true if the references point to objects that are equivalent. For example:
StringBuilder s1 = new StringBuilder(“fred”);
StringBuilder s2 = new StringBuilder(“fred”);
Console.WriteLine( s1 == s2 );
Console.WriteLine( s1.Equals(s2) );
will display:
False
True
s1 and s2 are different objects (hence == returns false), but they are equivalent (hence Equals() returns true).
Unfortunately there are exceptions to these rules. The implementation of Equals() in System.Object (the one you’ll inherit by default if you write a class) compares identity, i.e. it’s the same as operator==. So Equals() only tests for equivalence if the class author overrides the method (and implements it correctly). Another exception is the string class – its operator== compares value rather than identity.
Bottom line: If you want to perform an identity comparison use the ReferenceEquals() method. If you want to perform a value comparison, use Equals() but be aware that it will only work if the type has overridden the default implementation. Avoid operator== with reference types (except perhaps strings), as it’s simply too ambiguous.


6.8 How do I enforce const correctness in C#?

You can’t – at least not in the same way you do in C++. C# (actually, the CLI) has no real concept of const correctness, For example, there’s no way to specify that a method should not modify an argument passed in to it. And there’s no way to specify that a method does not modify the object on which it is acting.
To get a feel for the angst this causes among some C++ programmers, read the feedback on this post from Raymond Chen.
There are of course ways of addressing this issue. For example, see Brad Abram’s post (and associated feedback) for some ideas on adding optional read-only behaviour to collection classes.
7. C# 2.0
7.1 What are the new features in C# 2.0?
Support for all of the new framework features such as generics, anonymous methods, partial classes, iterators and static classes. See the .NET FAQ for more on these features.
Delegate inference is a new feature of the C# compiler which makes delegate usage a little simpler. It allows you to write this:
Thread t = new Thread(ThreadFunc);
instead of this:
Thread t = new Thread( new ThreadStart(ThreadFunc) );
Another minor but welcome addition is the explicit global namespace, which fixes a hole in namespace usage in C# 1.x. You can prefix a type name with global:: to indicate that the type belongs to the global namespace, thus avoiding problems where the compiler infers the namespace and gets it wrong.
Finally C# 2.0 includes some syntactic sugar for the new System.Nullable type. You can use T? as a synonym for System.Nullable, where T is a value type. As suggested by the name, this allows values of the type to be ‘null’, or ‘undefined’.
7.2 Are C# generics the same as C++ templates?
No, not really. There are some similarities, but there are also fundamental differences

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 versions of the 1.0 SDK and runtime were 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, and was mostly bug fixes for 1.0.
.NET 2.0 was released to MSDN subscribers in late October 2005, and was officially launched in early November.


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.
• SharpDevelop is a free IDE for C# and VB.NET.
• Microsoft Visual Studio Express editions are cut-down versions of Visual Studio, for hobbyist or novice developers.There are different versions for C#, VB, web development etc. Originally the plan was to charge $49, but MS has decided to offer them as free downloads instead, at least until November 2006.
• Microsoft Visual Studio Standard 2005 is around $300, or $200 for the upgrade.
• Microsoft VIsual Studio Professional 2005 is around $800, or $550 for the upgrade.
• At the top end of the price range are the Microsoft Visual Studio Team Edition for Software Developers 2005 with MSDN Premium and Team Suite editions.
You can see the differences between the various Visual Studio versions here.
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.


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 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.3 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.4 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.


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?
The terms ‘private’ and ‘shared’ refer to how an assembly is deployed, not any intrinsic attributes of the assembly.
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 intended to be used by multiple applications, and is normally stored in the global assembly cache (GAC), which is a central repository for assemblies. (A shared assembly can also be stored outside the GAC, in which case each application must be pointed to its location via a codebase entry in the application’s configuration file.) The main advantage of deploying assemblies to the GAC is that the GAC can support multiple versions of the same assembly side-by-side.
Assemblies deployed to the GAC must be strong-named. Outside the GAC, strong-naming is optional.
3.4 How do assemblies find each other?
By searching directory paths. There are several factors that can affect the path (such as the AppDomain host, and application configuration files), but for weakly named assemblies the search path is normally the application’s directory and its sub-directories. For strongly named assemblies, the search path is the GAC followed by the private assembly path.
3.5 How does assembly versioning work?
An assembly has a version number consisting of four parts, e.g. 1.0.350.1. These are typically interpreted as Major.Minor.Build.Revision, but this is just a convention.
The CLR applies no version constraints on weakly named assemblies, so the assembly version has no real significance.
For strongly named assemblies, the version of a referenced assembly is stored in the referring assembly, and by default only this exact version will be loaded at run-time. If the exact version is not available, the referring assembly will fail to load. It is possible to override this behaviour in the config file for the referring assembly – references to a single version or a range of versions of the referenced assembly can be redirected to a specific version. For example, versions 1.0.0.0 to 2.0.0.0 can be redirected to version 3.0.125.3. However note that there is no way to specify a range of versions to be redirected to. Publisher policy files offer an alternative mechanism for redirecting to a different version for assemblies deployed to the GAC – a publisher policy file allows the publisher of the assembly to redirect all applications to a new version of an assembly in one operation, rather than having to modify all of the application configuration files.
The restrictions on version policy for strongly named assemblies can cause problems when providing patches or ‘hot fixes’ for individual assemblies within an application. To avoid having to deploy config file changes or publisher policy files along with the hot fix, it makes sense to reuse the same assembly version for the hot fix. If desired, the assemblies can be distinguised by altering the assembly file version, which is not used at all by the CLR for applying version policy. For more discussion, see Suzanne Cook’s When to Change File/Assembly Versions blog entry.
Note that the versioning of strongly named assemblies applies whether the assemblies are deployed privately or to the GAC.
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.)
8.3 Who defines the CAS code groups?
Microsoft defines some default ones, but you can modify these and even create your own. To see the code groups defined on your system, run ‘caspol -lg’ from the command-line. On my system it looks like this:
Level = Machine

Code Groups:

1. All code: Nothing
1.1. Zone – MyComputer: FullTrust
1.1.1. Honor SkipVerification requests: SkipVerification
1.2. Zone – Intranet: LocalIntranet
1.3. Zone – Internet: Internet
1.4. Zone – Untrusted: Nothing
1.5. Zone – Trusted: Internet
1.6. StrongName –
0024000004800000940000000602000000240000525341310004000003
000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD06
F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E08
07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5C
AC1DF1734633C602F8F2D5: Everything
Note the hierarchy of code groups – the top of the hierarchy is the most general (‘All code’), which is then sub-divided into several groups, each of which in turn can be sub-divided. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission set than its parent.
8.4 How do I define my own code group?
Use caspol. For example, suppose you trust code from http://www.mydomain.com and you want it have full access to your system, but you want to keep the default restrictions for all other internet sites. To achieve this, you would add a new code group as a sub-group of the ‘Zone – Internet’ group, like this:
caspol -ag 1.3 -site http://www.mydomain.com FullTrust
Now if you run caspol -lg you will see that the new group has been added as group 1.3.1:

1.3. Zone – Internet: Internet
1.3.1. Site – http://www.mydomain.com: FullTrust

Note that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to manipulate from the command-line. The underlying runtime never sees it.


8.5 How do I change the permission set for a code group?

Use caspol. If you are the machine administrator, you can operate at the ‘machine’ level – which means not only that the changes you make become the default for the machine, but also that users cannot change the permissions to be more permissive. If you are a normal (non-admin) user you can still modify the permissions, but only to make them more restrictive. For example, to allow intranet code to do what it likes you might do this:
caspol -cg 1.2 FullTrust
Note that because this is more permissive than the default policy (on a standard system), you should only do this at the machine level – doing it at the user level will have no effect.
8.6 Can I create my own permission set?
Yes. Use caspol -ap, specifying an XML file containing the permissions in the permission set. To save you some time, here is a sample file corresponding to the ‘Everything’ permission set – just edit to suit your needs. When you have edited the sample, add it to the range of available permission sets like this:
caspol -ap samplepermset.xml
Then, to apply the permission set to a code group, do something like this:
caspol -cg 1.3 SamplePermSet
(By default, 1.3 is the ‘Internet’ code group)
8.7 I’m having some trouble with CAS. How can I troubleshoot the problem?
Caspol has a couple of options that might help. First, you can ask caspol to tell you what code group an assembly belongs to, using caspol -rsg. Similarly, you can ask what permissions are being applied to a particular assembly using caspol -rsp.
8.8 I can’t be bothered with CAS. Can I turn it off?
Yes, as long as you are an administrator. Just run:
caspol -s off


9. Intermediate Language (IL)
9.1 Can I look at the IL for an assembly?

Yes. MS supply a tool called Ildasm 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. Threads
11.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();

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


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

11.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.
12. Tracing
12.1 Is there built-in support for tracing/logging?

Yes, in the System.Diagnostics namespace. There are two main classes that deal with tracing – Debug and Trace. They both work in a similar way – the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.
12.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.
12.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.
12.4 Are there any third party logging components available?
Log4net is a port of the established log4j Java logging component.
13. Miscellaneous
13.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.
13.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.
13.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.
13.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.
13.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.
13.6 Will my .NET app run on 64-bit Windows?
64-bit (x64) versions of Windows support both 32-bit and 64-bit processes, and corresponding 32-bit and 64-bit versions of .NET 2.0. (.NET 1.1 is 32-bit only).
.NET 1.x apps automatically run as 32-bit processes on 64-bit Windows.
.NET 2.0 apps can either run as 32-bit processes or as 64-bit processes. The OS decides which to use based on the PE header of the executable. The flags in the PE header are controlled via the compiler /platform switch, which allows the target of the app to be specified as ‘x86’, ‘x64’ or ‘any cpu’. Normally you specify ‘any cpu’, and your app will run as 32-bit on 32-bit Windows and 64-bit on 64-bit Windows. However if you have some 32-bit native code in your app (loaded via COM interop, for example), you will need to specify ‘x86’, which will force 64-bit Windows to load your app in a 32-bit process. You can also tweak the 32-bit flag in the PE header using the SDK corflags utility.
Some more explanation here:
http://blogs.msdn.com/gauravseth/archive/2006/03/07/545104.aspx
http://blogs.msdn.com/joshwil/archive/2005/04/08/406567.aspx
http://msdn.microsoft.com/netframework/programming/64bit/gettingstarted/
13.7 What is reflection?
All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes – e.g. determining data type sizes for marshaling data across context/process/machine boundaries.
Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).
14. .NET 2.0
14.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.
14.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; i++ )
yield return rand.NextDouble();
}

int m_size = 0;
}
The use of ‘yield return’ is rather strange at first sight. It effectively synthethises an implementation of IEnumerator, something we had to do manually in .NET 1.x.
14.3 What’s the problem with .NET generics?
.NET generics work great for container classes. But what about other uses? Well, it turns out that .NET generics have a major limitation – they require the type parameter to be constrained. For example, you cannot do this:
static class Disposer
{
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
14.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:
• 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.
and many, many more. See http://msdn2.microsoft.com/en-us/library/t357fb32(en-US,VS.80).aspx for a comprehensive list of changes.

In C# you can define two types of variables: value types and reference types. With the value type of variable you can store actual values, while the reference type simply holds references to values that are stored somewhere in memory.
The first thing to understand is that value types are allocated on the stack and are available in almost all programming languages. Reference types are allocated on the heap and normally will represent class instances.
Predefined C# value types
sbyte: Holds 8-bit signed integers. The s in sbyte stands for signed, meaning that the variable’s value can be either positive or negative. The smallest possible value for ansbyte variable is -128; the largest possible value is 127.
byte: Holds 8-bit unsigned integers. Unlike sbyte variables, byte variables are not signed and can only hold positive numbers. The smallest possible value for a byte variable is 0; the largest possible value is 255.
short: Holds 16-bit signed integers. The smallest possible value for a short variable is -32,768; the largest possible value is 32,767.
ushort: Holds 16-bit unsigned integers. The u in ushort stands for unsigned. The smallest possible value of an ushort variable is 0; the largest possible value is 65,535.
int: Holds 32-bit signed integers. The smallest possible value of an int variable is -2,147,483,648; the largest possible value is 2,147,483,647.
uint: Holds 32-bit unsigned integers. The u in uint stands for unsigned. The smallest possible value of a uint variable is 0; the largest possible value is 4,294,967,295.
long: Holds 64-bit signed integers. The smallest possible value of a long variable is 9,223,372,036,854,775,808; the largest possible value is 9,223,372,036,854,775,807.
ulong: Holds 64-bit unsigned integers. The u in ulong stands for unsigned. The smallest possible value of a ulong variable is 0; the largest possible value is 18,446,744,073,709,551,615.
char: Holds 16-bit Unicode characters. The smallest possible value of a char variable is the Unicode character whose value is 0; the largest possible value is the Unicode character whose value is 65,535.
float: Holds a 32-bit signed floating-point value. The smallest possible value of a float type is approximately 1.5 times 10 to the 45th power; the largest possible value is approximately 3.4 times 10 to the 38th power.
double: Holds a 64-bit signed floating-point value. The smallest possible value of a double is approximately 5 times 10 to the 324th; the largest possible value is approximately 1.7 times 10 to the 308th.
decimal: Holds a 128-bit signed floating-point value. Variables of type decimal are good for financial calculations. The smallest possible value of a decimal type is approximately 1 times 10 to the 28th power; the largest possible value is approximately 7.9 times 10 to the 28th power.
bool: Holds one of two possible values, true or false. The use of the bool type is one of the areas in which C# breaks from its C and C++ heritage. In C and C++, the integer value 0 was synonymous with false, and any nonzero value was synonymous with true. In C#, however, the types are not synonymous. You cannot convert an integer variable into an equivalent bool value. If you want to work with a variable that needs to represent a true or false condition, use a bool variable and not an int variable.
Predefined C# reference types
string: Represents a string of Unicode characters. It allows easy manipulation and assignment of strings. Strings are immutable, meaning that once it is created it can’t be modified. So when you try to modify a string, such as concatenating it with another string, a new string object is actually created to hold the new resulting string.
object: Represents a general purpose type. In C#, all predefined and user-defined types inherit from the object type or System.Object class.
Summary
Proper usage of correct data types allows developers to make the most of the language, but may take some time for those who have used different programming languages prior to switching to C#

It supports both synchronous and asynchronous read and write operations
Streams involve three fundamental operations:
1. You can read from streams. Reading is the transfer of data from a stream into a data structure, such as an array of bytes.
2. You can write to streams. Writing is the transfer of data from a data structure into a stream.
3. Streams can support seeking. Seeking is the querying and modifying of the current position within a stream. Seek capability depends on the kind of backing store a stream has. For example, network streams have no unified concept of a current position, and therefore typically do not support seeking.
Stream is the abstract base class of all streams. A stream is an abstraction of a sequence of bytes, such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket.
Notes to Implementers When implementing a derived class of Stream, you must provide implementations for the Read and Write methods..

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe

Introduction to .net Framework 3.0

NET Framework 3.0, formerly called WinFX , includes a new set of managed code APIs that are an integral part of the upcoming

Windows Vista and Windows Server “Longhorn” operating systems.

.Net Framework is also available on Win XP SP2.Net Framework 3.0 consists of four new components

1. Windows Presentation Foundation :WPF is also called avalon. Avalon is a two-dimensional (2-D) and

three-dimensional (3-D) graphics engine with the following characteristics and

capabilities:

->> Contains many common user interface components, including buttons,sliders, and edit boxes
->> Does 2-D and 3-D animation
->> Contains hyperlinks (for navigating between documents) and tables
->> Provides various types of grids and panels to assist in layout
->> Has multipage fixed-format and flow-format document layout, styles, storyboards, timelines,
effects, data binding, and so on

Avalon uses the markup language called XAML. XAML is a declarative XML-based language that defines objects and their

properties in XML.When using XAML with Avalon, the procedural code (code behind) is separate from the user interface
(UI). The advantage to this approach is that it enables teams to work together at the same time.

below is the example of XAML



< ListBox Name=”lbox” Height=”127” Width=”154”>
 < ListBoxItem Name=”lBoxItem1” Background=”Aqua” Width=”100”>
< ContentControl.Content>
Item One
< /ContentControl.Content>
< ContentControl.Height>
30
< /ContentControl.Height>
< /ListBoxItem>
< ListBoxItem Name=”lBoxItem2”>
Item Two
< /ListBoxItem>
< ListBoxItem Name=”lBoxItem3” Content=”Item Three” />
< /ListBox>

2. Windows Communication Foundation (WCF) WCF is also called Indigo; a service-oriented messaging system which

allows programs to interoperate locally or remotely similar to web services.Here are the design goals of Indigo

->>Create a new unified communications API
->>Base it on service-oriented architecture
->>Provide a new and robust way of implementing Remoting and Web Services (WS)
->>Support most WS-* specifications.

3. Windows Workflow Foundation (WF): Windows Workflow Foundation (WF) is a Microsoft technology for defining,

executing and managing workflows. This technology is part of .NET Framework 3.0 and will be available natively in the Windows

Vista operating system. The technology will also be backported to the Windows XP and Windows 2003 Server operating systems.

The .NET Framework 3.0 “workflow runtime” provides common facilities for running and managing the workflows and can be hosted

in any CLR app domain. Windows Workflow Foundation is the client side component of BizTalk Server.

->> XAML is commonly used for declaring the structure of a workflow

4. Windows CardSpace Formerly known by its codename InfoCard, is a framework developed by Microsoft which

securely stores digital identities of a person, and provides an unified interface for choosing the identity for a particular

transaction, such as logging in to a website. Windows CardSpace is a central part of Microsoft’s effort to create an Identity

Metasystem, or an unified, secure and interoperable identity layer for the Internet.

What do you need to develop WindowFX development

–>>Windows Longhorn Client Beta 1, Windows XP Service Pack 2, or Windows Server 2003 (you
must also install components such as IIS)
–>> Visual Studio 2005 Beta 2
–>> SQL Server 2005
–>> WinFX Beta 1
–>> WinFX Beta 1 Software Developer Kit (SDK)
–>> Optional: Microsoft VirtualPC 2004. (In fact, it is strongly recommend that you use this product
to install any Beta product. You can download a trial version on the Microsoft Web site.)

Introduction to .NET with Basic Shotcuts and Secrets for the Beginner

Introduction

.NET is a new environment for developing and running software applications, featuring ease of development of web-based services, rich standard runtime services available to component written in variety of programming languages and inter-language and intermaching interoperability.

What lead to the development of .NET?

C and C++ Application are Monolithic Applications. In these types of applications the entire business logic is in .exe files.

Then the Software society needed a new tier to seperate the database. This led to a new architecture 2-Tier Architecture. In this architecture, Client sending data to the server needs Validation rules. The only disadvantage with this architecture is If there is any change in the logic everything should be done on the client side.

Then came a new architecture,3-Tier Architecture. In this architecture Client acts as a simple User Interface. Client,Business layer,Server(database) comprises of 3-tier architecture. .NET is meant for generating 3-tier architectures (Server side Programming).

There are many problems with Server Side Applications:
1) Memory Management
2) Security
3) Exception Handling
4) Strict Type Checking

How .NET solves Server Side Application Problems?


1) Memory Management:
Any object that has no reference has to be deleted to save memory. .NET provide powerful Garbage collector.

2) Security :
.NET provides both Userlevel Security and Code level Security.

3) Exception Handling:
.NET provides Exception handler, which alerts about the exception rather than crashing the application.

4) Strict Type Checking:
.NET provides strong Type Checker unlike the conventional way of fooling the compiler at compile time resulting in absurd output.

There are many other interesting features in .NET like CLR with components like Class loader, Code Manager, Garbage Collector, Security Engine , COM Marshaler and Base Class Library Support etc.,

Secrets

Multiple versions of .NET Framework can be installed on the server.

Fonts can be changed in IDE through Tools -> Options Environment folder-> Fonts and colors

Code snippets can be stored within Toolbox Window. Select code and drag and drop in the ToolBox Window. It can be in HTML Section or General Section.

Commenting large Section of code Ctrl+K+C
UnCommenting Ctrl+K+U

Tired of working on Enterprise Manager everytime there is a change in the database. Here’s a simple solution…One can make use of the Server Explorer in the IDE to change the table or to run a query and can work with Event Logs and many more advanced properties.

Q)Which layout is preferred in web application involving data from the database?
Flow Layout.
Grid Layout has problems with repeater control( falls in the upper right corner as the css positioning is designed in such a way) and DataGrid (Datagrid grows as the data is populated dynamically underneath the bottom of page and if any button is used, there are further problems (try it out !!!)

Q)Can we use both FlowLayout and GridLayout modes Together?
Yes

Benefits of Framework 2.0

1) Improved were scenarios like Data set insertion and multi-threaded scenarios (such as ASP.NET applications) using SqlDataReader (25% better or more, depending on hardware and OS architecture).
2) The new generation of 64-bit computers enables the creation of applications that can run faster and take advantage of more memory than is available to 32-bit applications.
3) An access control list (ACL) is used to grant or revoke permission to access a resource on a computer. New classes have been added to the .NET Framework that allow managed code to create and modify an ACL, and new members that utilize an ACL have been added to the I/O, registry, and threading classes.
4) New features in ADO.NET include support for:
a. user-defined types (UDT)
b. asynchronous database operations
c. XML data types
d. large value types
e. snapshot isolation
f. Allow applications to support Multiple Active Result Sets (MARS) with SQL Server 2005 code named Yukon.
5) The capability of assigning the long-running operation to a background thread gives the foreground thread the ability to remain active throughout the operation. (Asynchronous Processing) This can include following areas
a. File IO, Stream IO, Socket IO
b. Networking: HTTP, TCP
c. Remoting channels (HTTP, TCP) and proxies
d. XML Web services created using ASP.NET
e. ASP.NET Web Forms
f. Message Queuing using the MessageQueue Class.
g. Asynchronous delegates
6) Database cache invalidation-You can cache an item…and set it to invalidate if the underlying datasource changes. Really helpful on a website where you can cache data on your pages and then if the database table changes your cache will expire and the next request to the page will get new data and then cache it until it changes.
7) Performance will increase drastically with SQL dependency cache. Also you can improve your performance even more with asynchronous call backs. The pre-JITter, NGen, has considerably improved.
8) Improvements in security support include:
a. You don’t need to drop to the Win32 API as much when dealing with X509 certificates or XML encryption – the support is now there in the Framework.
b. There is a new data protection API. This means, amongst other things, that you can now encrypt file contents with just one or two lines of code.
c. There is new support for access control lists (ACLs)
9) Ajax (Asynchronous JavaScript and XML) is the new feature which is introduce in the framework 2.0

A glance at .NET Framework 3.0

In the programming field, .NET is the most successful development platform..Net Framework 2.0 is enough to satisfy for most of us. .NET Framework 3.0 came with many new and useable features. With .NET Framework 3.0, developers feel more easy when develops. In the new version of .NET, there is nothing new with CLR (Common Language runtime) but it introduces four new technologies.Are we not apprehensive about accepting anything newer, especially if that is going to deprecate the existing one?The latest versions of .NET are .NET Framework 3.0. Programming with .NET Framework 3.0 become more advance.It is built with all the advantage of .NET framework 2.0, and is all set to bring in a paradigm shift in the way we write our applications today. When we go to develop any application then the main goal we set is, to create the Best application in least amount of time. The .NET Framework 3.0 will still ship with Windows Vista, and will be available down-level for Windows XP and Windows Server 2003 as planned.This newly released framework was earlier named as WinFx! .NET Framework 3.0 , compromise of familiar .NET Framework2.0 components (ASP.NET, ADO.NET, Window Forms etc).There are four new technologies in .NET Framework 3.0. These technologies are added to face the new challenge of software development. These new complementary technologies are added to address some of the most arduous challenges of contemporary software development.


The New in .NET Framework 3.0


Here .NET Framework 3.0 is same like as .NET Framework 2.0, but with some new technology and feature. The entire features are same in new framework, which was in .NET Framework 2.0. The .NET 3.0 introducing four new foundation technologies:

*
Windows Presentation Foundation (WPF)
*
Windows Communication Foundation (WCF)
*
Windows Workflow Foundation (WWF)
*
Windows CardSpace (WCS)

While the .NET Framework 2.0 class library is partially superseded by the new components (WF, WCF, and WPF) added in version 3.0, many portions of the original class library are still crucial to developers. The technologies of version 2.0 (ASP.NET, WinForms, ADO.NET, XML etc.) largely remain the elementary part of the new release; however, the developer of .NET Framework 3.0, mostly use WPF over windows Forms.

Windows Workflow Foundation (WF)


Windows Workflow Foundation (WWF) is a Microsoft technology for defining, executing, and managing workflows. Workflow as it name implies. It shows the flow of work; mean how the work is going, how activities are performing. WF provides such a common workflow technology for Windows.If we have to make workflow enabled application on windows then we use Windows Workflow Foundation.

System.Workflow is the namespace of Windows Workflow Foundation in Microsoft .NET Framework version 3.0. Windows Workflow Foundation provides full support for Visual Basic .NET and C#, debugging, a graphical workflow designer and the ability to develop our workflow completely in code. A workflow is a set of activities stored as a model that describe a real world process. Each Activity can be represented as a class.By using this we can reuse that activity easily. With WF, we can understand with our flow of operation. We can easily understand with our all activity.

Windows Presentation Foundation (WPF)

The Windows Presentation Foundation (WPF), also named Avalon, is the graphical subsystem feature of the .NET Framework 3.0. WPF is a consistent programming model for building solutions, and enables the use of richer controls, design, and development in Windows programs. In most windows application user interface play an important role .A developer needs to use Windows Forms to build a Windows GUI, or HTML/ASPX/Applets/JavaScript etc. Developer’s job become tough here when he go to, building a coherent user interface for different kinds of clients using diverse technologies isn’t a simple job. WPF provide consistent platform for these entire user interface aspects to solve the problem. WPF support video, animation, 2/3D graphics, and various kinds of documents.

Windows Communication Foundation (WCF)

WCF means programmes can communicate between each other either they are on same computer or in networking .Windows Communication Foundation is a communications infrastructure built around the Web services architecture. When the application becomes built then most of the application need to communication between each other. This was a big problem in last few years, so all vendors becomes agreed to support SOAP based web services, which make interoperability between application, either they are from same platforms or different platforms.The WCF programming model unifies web services, .NETRemoting,distributed transactions, and message queues into a single service-oriented programming model for distributed computing. However, instead of requiring developers to use a different technology with a different application programming interface for each kind of communication, WCF provides a common approach and API. WCF provides strong support for interoperable communication through SOAP.

Windows CardSpace (WCS)

Windows CardSpace (InfoCard) is a Digital Identity to online services. Digital Identity means how user will electronically represent them. Like as a debit/credit card each card has digital identity and password. If any user go to use the site on internet then he enter their username and password, for identity, but this is not secure. To reduce these types of problems WCS works. WCS (originally called Info Card) helps people keep track of their digital identities as distinct information cards. If a Web site accepts WCS logins, users attempting to log in to that site will see a WCS selection. By choosing a card, users also choose a digital identity that will be used to access this site. CardSpace and the new supporting technologies will change how you authenticate into an application, whether it sits on the Web, your phone, or your desktop.

Benefits of framework 3.0/3.5

1) Fire fox support
2) Windows Presentation Foundation provides rich capability for rendering objects and user interfaces in client applications.
3) Windows CardSpace, which is useful in developing single sign-on applications, ensures that users don’t have to continually type in ID and passwords.
4) Windows Workflow Foundation provides a tool chest for developing workflow into applications.
5) Windows Communication Foundation offers a way to exchange data among applications structured as a service-oriented architecture.
6) As a whole, the .NET Framework 3.0 also better exposes the capabilities for providing better cohesion between desktops and data centers.
7) The Microsoft AJAX Library supports client-centric, object-oriented development, which is browser-independent. By using the library classes in your ECMAScript (JavaScript) you can enable rich UI behaviors without roundtrips to the server.
8) Pipes provide interprocess communication between any processes running on the same computer, or on any other Windows computer within a network. The .NET Framework provides access to two types of pipes: anonymous pipes and named pipes. For more information about pipes, see Pipes.
9) The new ReaderWriterLockSlim class provides performance that is significantly better than ReaderWriterLock, and comparable with the lock statement (SyncLock in Visual Basic). Transitions between lock states have been simplified to make programming easier and to reduce the chances of deadlocks. The new class supports recursion to simplify migration from lock and from ReaderWriterLock.
10) Peer-to-peer networking is a serverless networking technology that allows several network devices to share resources and communicate directly with each other.
11) The .NET Framework 3.5 unifies the Windows Workflow Foundation (WF) and Windows Communication Foundation (WCF) frameworks so that you can use WF as a way to author WCF services or expose your existing WF workflow as a service. This enables you to create services that can be persisted, can easily transfer data in and out of a workflow, and can enforce application-level protocols.
12) WCF and ASP.NET AJAX Integration is integration of WCF with the Asynchronous JavaScript and XML (AJAX) capabilities in ASP.NET provides an end-to-end programming model for building Web applications that can use WCF services. In AJAX-style Web applications, the client (for example, the browser in a Web application) exchanges small amounts of data with the server by using asynchronous requests.
13) Windows Presentation Foundation contains changes and improvements in numerous areas, including versioning, the application model, data binding, controls, documents, annotations, and 3-D UI elements.
14) Existing Windows Forms applications work seamlessly on Windows Vista, and they are upgraded to have the same appearance as applications written specifically for Windows Vista whenever possible.
15) LINQ extends powerful query capabilities to the language syntax of C# and Visual Basic in the form of standard, easily-learned query patterns. This technology can be extended to support potentially any kind of data store. The .NET Framework 3.5 includes LINQ provider assemblies that enable the use of LINQ for querying .NET Framework collections, SQL Server databases, ADO.NET Datasets, and XML documents.
16) ADO.NET gets paging support as well as synchronization from caches at local and server datastores. Also performance improvements for multicore CPUs

.net framework

Net Framework1.0: –

This is the initial version of Microsoft .NET Framework.

************
.Net Framework 1.1: –

This is the major upgrade to the .NET Framework 1.0 to provide:

1) .NET Compact Framework – a version of the .NET Framework for small devices
2) Internet Protocol version 6 (IPv6) support
3) Built-in support for ODBC and Oracle databases: previously available as an add-on for .NET Framework 1.0, now part of the framework
4) Built-in support for mobile ASP.NET controls: previously available as an add-on for .NET Framework, now part of the framework
5) Security changes: enable Windows Forms assemblies to execute in a semi-trusted manner from the Internet and enable Code Access Security in ASP.NET applications
6) Numerous API changes and many more

************
.Net Framework 2.0: –

This version shipped with Microsoft Windows Server 2003 Release Candidate [RC]. This is the last version with support for Microsoft Windows 2000.

Changes in .NET Framework since 1.1:

1) Full 64-bit support for both the x64 and the IA64 hardware platforms.
2) Language support for Generics built directly into the .NET CLR.
3) Many additional and improved ASP.NET web controls.
4) New data controls with declarative data binding.
5) New personalization features for ASP.NET, such as support for themes, skins and webparts.
6) Numerous API changes and many more.

Microsoft started development on the .NET Framework in the late 1990s originally under the name of Next Generation Windows Services (NGWS). By late 2000 the first beta versions of .NET 1.0 were released.[16]

The .NET Framework stack.Version Version Number Release Date
1.0 1.0.3705.0 2002-01-05
1.1 1.1.4322.573 2003-04-01
2.0 2.0.50727.42 2005-11-07
3.0 3.0.4506.30 2006-11-06
3.5 3.5.21022.8 2007-11-19

A more complete listing of the releases of the .NET Framework may be found on the .NET Framework version list.

[edit] .NET Framework 1.0
This is the first release of the .NET Framework. Released on February 13, 2002. Available for Windows 98, NT 4.0, 2000, and XP. Mainstream support by Microsoft for this version ended July 10th, 2007, and extended support ends July 14th, 2009.[17]

[edit] .NET Framework 1.1
This is the first major .NET Framework upgrade. It is available on its own as a redistributable package or in a software development kit, and was published on April 3, 2003. It is also part of the second release of Microsoft Visual Studio .NET (released as Visual Studio .NET 2003). This is the first version of the .NET Framework to be included as part of the Windows operating system, shipping with Windows Server 2003. Mainstream support for .NET Framework 1.1 ends on October 14th, 2008, and extended support ends on October 8th, 2013. Since .NET 1.1 is a component of Windows Server 2003, extended support for .NET 1.1 on Server 2003 will run out with that of the OS – currently June 30th, 2013.

[edit] Changes since 1.0
Built-in support for mobile ASP.NET controls. Previously available as an add-on for .NET Framework, now part of the framework.
Security changes – enable Windows Forms assemblies to execute in a semi-trusted manner from the Internet, and enable Code Access Security in ASP.NET applications.
Built-in support for ODBC and Oracle databases. Previously available as an add-on for .NET Framework 1.0, now part of the framework.
.NET Compact Framework – a version of the .NET Framework for small devices.
Internet Protocol version 6 (IPv6) support.
Numerous API changes.

[edit] .NET Framework 2.0
Released with Visual Studio 2005, Microsoft SQL Server 2005, and BizTalk 2006.

The 2.0 Redistributable Package can be downloaded for free from Microsoft, and was published on 2006-01-22.
The 2.0 Software Development Kit (SDK) can be downloaded for free from Microsoft.
It is included as part of Visual Studio 2005 and Microsoft SQL Server 2005.
Version 2.0 is the last version with support for Windows 2000, Windows 98 and Windows Me.
It shipped with Windows Server 2003 R2 (not installed by default).

[edit] Changes since 1.1
Numerous API changes.
A new hosting API for native applications wishing to host an instance of the .NET runtime. The new API gives a fine grain control on the behavior of the runtime with regards to multithreading, memory allocation, assembly loading and more (detailed reference). It was initially developed to efficiently host the runtime in Microsoft SQL Server, which implements its own scheduler and memory manager.
Full 64-bit support for both the x64 and the IA64 hardware platforms.
Language support for generics built directly into the .NET CLR.
Many additional and improved ASP.NET web controls.
New data controls with declarative data binding.
New personalization features for ASP.NET, such as support for themes, skins and webparts.
.NET Micro Framework – a version of the .NET Framework related to the Smart Personal Objects Technology initiative.

[edit] .NET Framework 3.0
.NET Framework 3.0, formerly called WinFX,[18] includes a new set of managed code APIs that are an integral part of Windows Vista and Windows Server 2008 operating systems. It is also available for Windows XP SP2 and Windows Server 2003 as a download. There are no major architectural changes included with this release; .NET Framework 3.0 uses the Common Language Runtime of .NET Framework 2.0.[19] Unlike the previous major .NET releases there was no .NET Compact Framework release made as a counterpart of this version.

.NET Framework 3.0 consists of four major new components:

Windows Presentation Foundation (WPF), formerly code-named Avalon; a new user interface subsystem and API based on XML and vector graphics, which uses 3D computer graphics hardware and Direct3D technologies. See WPF SDK for developer articles and documentation on WPF.
Windows Communication Foundation (WCF), formerly code-named Indigo; a service-oriented messaging system which allows programs to interoperate locally or remotely similar to web services.
Windows Workflow Foundation (WF) allows for building of task automation and integrated transactions using workflows.
Windows CardSpace, formerly code-named InfoCard; a software component which securely stores a person’s digital identities and provides a unified interface for choosing the identity for a particular transaction, such as logging in to a website.

[edit] .NET Framework 3.5
Version 3.5 of the .NET Framework was released on November 19, 2007, and is included with Windows Server 2008. As with .NET Framework 3.0, version 3.5 uses the CLR of version 2.0. In addition, it installs .NET Framework 2.0 SP1 and .Net Framework 3.0 SP1, which adds some methods and properties to the BCL classes in version 2.0 which are required for version 3.5 features such as Language Integrated Query (LINQ). These changes do not affect applications written for version 2.0, however.[20]

As with previous versions, a new .NET Compact Framework 3.5 was released in tandem with this update in order to provide support for additional features on Windows Mobile and Windows Embedded CE devices.

The source code of the Base Class Library in this version has been partially released under Microsoft Reference License.[1]

[edit] Changes since version 3.0
New language features in C# 3.0 and VB.NET 9.0 compiler
Adds support for expression trees and lambda methods
Extension methods
Expression trees to represent high-level source code at runtime.[21]
Anonymous types with static type inference
Language Integrated Query (LINQ) along with its various providers
LINQ to Objects
LINQ to XML
LINQ to SQL
Paging support for ADO.NET
ADO.NET synchronization API to synchronize local caches and server side datastores
Asynchronous network I/O API[21]
Peer-to-peer networking stack, including a managed PNRP resolver[22]
Managed wrappers for WMI and Active Directory APIs[23]
Enhanced WCF and WF runtimes, which let WCF work with POX and JSON data, and also expose WF workflows as WCF services.[24] WCF services can be made stateful using the WF persistence model.[21]
Support for HTTP pipelining and syndication feeds.[24]
ASP.NET AJAX is included
New System.CodeDom namespace.

[edit] SP1 (codename “Arrowhead”)
.NET Framework 3.5 SP1, codenamed “Arrowhead”, will reportedly enhance support for occasionally connected applications[25], and provide built-in support for the Microsoft ASP.NET Model-View-Controller (MVC) Framework.[26] “Arrowhead” will[27] increase the cold-start performance (startup when no other .NET Framework application has been started previously) of .NET Framework applications, by as much as 25 – 40%.[28] It will also hardware accelerate some WPF effects such as shadows, as well as general performance and API enhancements across the WPF stack. In addition, a set of WPF controls, including a DataGrid will also be included.[28] ADO.NET Entity Framework has also been added [29] which gives the database based application programmer a ORM (Object Relational Mapping) tool.

The easiest way to determine which versions of the .NET Framework are installed on a computer is to locate the %systemroot%\Microsoft.NET\Framework folder. You can paste the listed address for the Framework folder into a Windows Explorer address bar to navigate to the Framework folder. The three released versions of the .NET Framework are contained in the following folders:
• v1.0.3705
• v1.1.4322
• v2.0.50727
Note If you see other directories that have a vN.N.NXXXX format that are not listed in this article, the versions may be beta versions or pre-released versions of the .NET Framework.

To determine which versions of the .NET Framework are installed on a computer, follow these steps:1. Open any one of the folders in the previous list, and then locate the Mscorlib.dll file.
2. Right-click the file, and then click Properties.
3. Click the Version tab, and then note the file version.
4. Use the previous list to determine which version of the .NET Framework is installed on the computer, and then click OK.

Repeat these steps for each version of the .NET Framework on the computer.

Microsoft .NET Framework redistributable package installs the .NET Framework runtime and associated files required to run applications developed to target the .NET Framework.

The primary focus of Microsoft .NET Framework 1.1 Service Pack 1 (SP1) is improved security. In addition, the service pack includes roll-ups of all reported customer issues found after the release of the Microsoft .NET Framework 1.1. Of particular note, SP1 provides better support for consuming WSDL documents, Data Execution prevention and protection from security issues such as buffer overruns. SP1 also provides support for Windows XP Service Pack 2 to provide a safer, more reliable experience for customers using Windows XP.

The Microsoft .NET Framework 3 is the new managed code programming model for Windows®. It combines the power of the .NET Framework version 2.0 with new technologies for building applications that have visually compelling user experiences, seamless communication across technology boundaries, and the ability to support a wide range of business processes. These new technologies are Windows Presentation Foundation, Windows Communication Foundation, Windows Workflow Foundation, and Windows CardSpace.
The .NET Framework 3 is included as part of the Windows Vista operating system; you can install it or uninstall it using Windows Features Control Panel. This redistributable package is for Windows XP and Windows Server 2003.

Basic .Net Framework

Introduction

This article contain detailed description of .Net Framework and its function. This article very useful to the .net beginners.

Intermediate Language (IL)

The (IL)Intermediate Language also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language), .NET source code is compiled to IL. This IL is converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

Common Language Runtime (CLR)

The CLR is Common Language Runtime and it forms the heart of the .NET framework. All languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. The CLR responsibilities are

a/ Intermediate language
b/ Code Verification
c/ Garbage Collection
d/ Code Access Security

Common Type System (CTS) and Common Language Specification (CLS)

The CTS can be used to accept other languages through the .net platform. Its contain all type of
datatypes and the possible coding or programing structure. The .Net supports nearly twenty languages
by this concept. This is a subset of the CTS which all .NET languages are expected to support.It was always a dream of microsoft to unite all different languages in to one umbrella and CLS is one step towards that.Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.

Managed Code

Managed code runs inside the environment of CLR i.e. .NET runtime.In short all IL are managed
code.But if you are using some third party software example VB6 or VC++ component they are
unmanaged code as .NET runtime (CLR) does not have control over the source code execution
of the language.

Assembly

Assembly is unit of deployment like EXE or a DLL. An assembly is completely self-describing.An assembly contains metadata information, which is used by the CLR for everything from type checking and security to actually invoking the components methods.As all information is in assembly itself it is independent of registry.This is the basic advantage as compared to COM where the version was stored in registry. In shared assembly deployment, an assembly is installed in the Global Assembly Cache (or GAC). The GAC contains shared assemblies that are globally accessible to all .NET applications on the machine.

NameSpace

NameSpace Logically group types. In Object Oriented world may times its possible that programmers will use the same class name.By qualifying NameSpace with classname this collision can be removed. Example System.Web.UI logically groups our UI related features.

Manifest

Assembly metadata is stored in Manifest. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a stand-alone PE file that contains only assembly manifest information.

>

How to reflection using ASP.NET 2.0 and C#.NET

This tutorial demonstrates how to go get class’s property value and invoke class’s method with Reflection.

Reflection provides objects (of type Type) that encapsulate assemblies, modules and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties. If you are using attributes in your code, Reflection enables you to access them.
First, you will need to import the System. Reflection namespace

using System.Reflection;

We are using Server Intellect and have found that by far, they are the most friendly, responsive, and knowledgeable support team we’ve ever dealt with!

The System.Reflection namespace contains classes and interfaces that provide a managed view of loaded types, methods, and fields, with the ability to dynamically create and invoke types.
We use btnGetProperty_Click to get the property value of the class InstanceClass. And we use btnInvoke_Click to invoke the function getFunction of the class InstanceClass. The code as follows.

protected string getObjectProperty(string str)
{

string retValue = “”;
try
{

object o = Activator.CreateInstance(type, new object[] { this.txtPropertyValue.Text.Trim()});
PropertyInfo pi = type.GetProperty(“ReturnValue”, typeof(string));
retValue = pi.GetValue(o, null).ToString();

}
catch (Exception ex)
{

Console.WriteLine(ex.Message);

}
return retValue;

}

protected string getOjbectMethod(string str)
{

object retValue = null;
try
{

object o = Activator.CreateInstance(type);
MethodInfo mi = type.GetMethod(“getFunction”, BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(string)},null);
retValue = mi.Invoke(o, new object[] { str });

}
catch (Exception ex)
{

Console.WriteLine(ex.Message);

}
return retValue.ToString();

}

protected void btnGetProperty_Click(object sender, EventArgs e)
{

this.lblPropertyResult.Text = this.getObjectProperty(this.txtPropertyValue.Text.Trim());

}

protected void btnInvoke_Click(object sender, EventArgs e)
{

this.lblInvokeResult.Text = this.getOjbectMethod(this.txtParameter.Text.Trim());

}

Add one custom class InstanceClass in this example.The code as follows:

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public class InstanceClass
{

private string _returnValue = “”;
public string ReturnValue
{

get { return “You input value is:”+_returnValue; }
set { _returnValue = value; }

}
public InstanceClass()
{

}
public InstanceClass(string str)
{

this._returnValue = str;

}
public string getFunction(string str)
{

return “You input value is:” + str;

}

}

We moved our web sites to Server Intellect and have found them to be incredibly professional. Their setup is very easy and we were up and running in no time.

The front end ReflectionCsharp.aspx page looks something like this:

<table style=”width: 708px”>

<tr>

<td style=”width: 68px”>PropertyValue:</td>
<td style=”width: 100px”>
<asp:TextBox ID=”txtPropertyValue” runat=”server”></asp:TextBox></td>
<td style=”width: 53px”>MethodParameter:</td>
<td style=”width: 100px”>
<asp:TextBox ID=”txtParameter” runat=”server”></asp:TextBox></td>

</tr>
<tr>

<td colspan=”2″>
<asp:Button ID=”btnGetProperty” runat=”server” OnClick=”btnGetProperty_Click” Text=”GetPropertyValue” /></td>
<td colspan=”2″>
<asp:Button ID=”btnInvoke” runat=”server” OnClick=”btnInvoke_Click” Text=”InvokeMethod” /></td>

</tr>
<tr>

<td style=”width: 68px; height: 21px”>Result:</td>
<td style=”width: 100px; height: 21px; text-align: left;”>
<asp:Label ID=”lblPropertyResult” runat=”server” ForeColor=”Red” Width=”258px”></asp:Label></td>
<td style=”width: 53px; height: 21px”>Result:</td>
<td style=”width: 100px; height: 21px;text-align: left;”>
<asp:Label ID=”lblInvokeResult” runat=”server” ForeColor=”Red” Width=”229px”></asp:Label></td>

</tr>

</table>

I just signed up at Server Intellect and couldn’t be more pleased with my Windows Server! Check it out and see for yourself.

The flow for the code behind page is as follows.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Reflection;

public partial class _Default : System.Web.UI.Page
{

private Type type = null;
protected void Page_Load(object sender, EventArgs e)
{

type = typeof(InstanceClass);

}

protected string getObjectProperty(string str)
{

string retValue = “”;
try
{

object o = Activator.CreateInstance(type, new object[] { this.txtPropertyValue.Text.Trim()});
PropertyInfo pi = type.GetProperty(“ReturnValue”, typeof(string));
retValue = pi.GetValue(o, null).ToString();

}
catch (Exception ex)
{

Console.WriteLine(ex.Message);

}
return retValue;

}

protected string getOjbectMethod(string str)
{

object retValue = null;
try
{

object o = Activator.CreateInstance(type);
MethodInfo mi = type.GetMethod(“getFunction”, BindingFlags.Public | BindingFlags.Instance, null, new Type[] { typeof(string)},null);
retValue = mi.Invoke(o, new object[] { str });

}
catch (Exception ex)
{

Console.WriteLine(ex.Message);

}
return retValue.ToString();

}

protected void btnGetProperty_Click(object sender, EventArgs e)
{

this.lblPropertyResult.Text = this.getObjectProperty(this.txtPropertyValue.Text.Trim());

}

protected void btnInvoke_Click(object sender, EventArgs e)
{

this.lblInvokeResult.Text = this.getOjbectMethod(this.txtParameter.Text.Trim());

}

}

Security is one of the most important concerns in application software development. Building a robust security model is one of the most important factors that drive the success of application software. As far as security in ASP.NET is concerned, three terms come into my mind, i.e., Authentication, Authorization and Impersonation. Put simply, authentication authenticates the user’s credentials and authorization relates to the resources that an authenticated user has access to. This article is the first in a series of articles on ASP.NET security and discusses these concepts and their applicability.

Let us start our discussion with a brief outline on the sequence of events are as far as authentication and authorization are concerned when a new request comes in. When a new request arrives at IIS, it first checks the validity of the incoming request. If the authentication mode is anonymous (default) then the request is authenticated automatically. But if the authentication mode is overridden in the web.config file settings, IIS performs the specified authentication check before the request is passed on to ASP.NET.

ASP.NET then checks whether Impersonation is enabled or not. We will discuss impersonation later in this article. If impersonation is enabled, ASP.NET executes with the identity of the entity on behalf of which it is performing the task; otherwise, the application executes with the identity of the IIS local machine and the privileges of the ASP.NET user account. Finally, the ASP.NET engine performs an authorization check on the resources requested by the authenticated user and if the user is authorized, it returns the request through IIS pipeline.
The following section discusses Authentication, Authorization and Impersonation and how we can implement them in ASP.NET applications.

Authentication
Authentication determines whether a user is valid or not based on the user’s credentials. Note that a user can be authorized to access the resources provided the user is an authenticated user. The application’s web.config file contains all of the configuration settings for an ASP.NET application. An authentication provider is used to prove the identity of the users in a system.
There are three ways to authenticate a user in ASP.NET:
* Forms authentication
* Windows authentication
* Passport authentication

Forms Authentication
This is based on cookies where the user name and the password are stored either in a text file or a database. It supports both session and persistent cookies. After a user is authenticated, the user’s credentials are stored in a cookie for use in that session. When the user has not logged in and requests for a page that is secured, he or she is redirected to the login page of the application. The following code snippet illustrates how this can be implemented in ASP.NET.

Note that the symbol “?” indicates all Non Authenticated and Anonymous users. Typically, the user enters the username and the password, clicks the login button and the form validates the values against values from that stored in a persistent store, usually a database. The following code snippet illustrates how this can be validated.

String username = txtUserName.Text;
String password = txtPassword.Text;
bool isUserValid = false;
//Code to validate the user name and password

if(isUserValid)
{
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False);

else // User is not valid

lblMessage.Text = “Invalid login…”;
}

The RedirectFromLoginPage method creates an authentication ticket and is used to redirect an authenticated user back to the originally requested URL or the default URL. The following code snippet illustrates how we can specify the user’s credentials in the application’s web.config file.

However you choose the above technique of authentication you should provide a means of encrypting the configuration file for security reasons. I will discuss these and other issues in the forthcoming articles in this series of articles on ASP.NET Security.

You can also use Forms Authentication to verify the user’s credentials using a database where the user’s credentials are stored. The following code example illustrates how this can be achieved. The method ValidateUserCredentials accepts a user name and the password, connects to the database where the user’s credentials is stored and verifies whether the supplied user’s credentials are correct.

private bool ValidateUserCredentials(String userName, String password)
{
// Connect to the database where the user credentials are stored and then verify whether the user’s credentials that
// are passed as parameters to this method are correct. The method would return true if success, false otherwise.
}

The above method can be called as illustrated in the code snippet below.

bool isAuthenticatedUser = false;
try
{
isAuthenticatedUser = ValidateUserCredentials(txtUserName.Text,txtPassword.Text);
}
catch(Exception ex)
{
//Some typical exception handling code
}

if (isAuthenticatedUser = = true )
{
//The user is authenticated, hence, redirect to the appropriate web form and/or display appropriate messages to the user
}

else
{
//Display appropriate messages to the user indicating that the user is not authenticated
}

Windows Authentication
Windows Authentication is used to validate a user based on the user’s Windows Account; however, this is only applicable in intranet environments where the administrator has full control over the users in the network. The following code snippet illustrates how we can implement Windows Authentication in ASP.NET.

Note that the symbol “*” indicates all users inclusive of Authenticated and Anonymous users.
Windows authentication can be of the following types
* Anonymous Authentication
* Basic Authentication
* Digest Authentication
* Integrated Windows Authentication

1. In the Anonymous Authentication mode IIS allows any user to access an ASP.NET application without any authentication checking.
2. In Basic Authentication mode users will be required to provide the Windows user name and password; however, this is very insecure.
3. The Digest Authentication mode is identical to Basic Authentication with the exception that the password is hashed before it is sent across the network.
4. In Integrated Windows Authentication mode, the passwords are not sent across the network; rather, the application uses some network authentication protocols for it to operate.

Passport Authentication
Passport authentication is a centralized authentication service that uses Microsoft’s Passport Service to authenticate the users of an application. It allows the users to create a single sign-in name and password to access any site that has implemented the Passport single sign-in (SSI) service. The following code snippet illustrates how we can implement Passport Authentication in ASP.NET.

Authorization
Authorization is the process of determining the accessibility to a resource for a previously authenticated user. Note that authorization can only work on authenticated users, hence ensuring that no un-authenticated user can access the application. The syntax for specifying authorization in ASP.NET is as follows.

In ASP.NET, there are the following types of authorizations.

* URL Authorization
* File Authorization
* Authorization based on ACLs (Access Control List)

1. File Authorization is performed by the FileAuthorizationModule, and is active when the application is configured to use Windows authentication. It checks the access control list ( ACL ) of the file to determine whether a user should have access to the file. ACL permissions are verified for the Windows identity or, if impersonation is enabled, for the Windows identity of the ASP.NET process.

2. URL authorization is performed by the URLAuthorizationModule, which maps users and roles to URLs in ASP.NET applications. This module can be used to selectively allow or deny access to arbitrary parts of an application (typically directories) for specific users or roles.”
3. Authorization like authentication is specified in the web.config file of the application. The following is an example of how we can use authorization in ASP.NET using the application’s configuration file.

It is also possible to specify the location to which the authorization settings defined in that particular location is applicable. Refer to the following code snippet that illustrates this.

You can also restrict or grant a GET or POST to one or more users of the ASP.NET application. The following code snippet illustrates how we can allow the user “Kapil” to do a POST while the other users can do only a GET.

Impersonation

According to MSDN, “When using impersonation, ASP.NET applications can optionally execute with the identity of the client on whose behalf they are operating. The usual reason for doing this is to avoid dealing with authentication and authorization issues in the ASP.NET application code. Instead, you rely on Microsoft Internet Information Services (IIS) to authenticate the user and either pass an authenticated token to the ASP.NET application or, if unable to authenticate the user, pass an unauthenticated token. In either case, the ASP.NET application impersonates whichever token is received if impersonation is enabled. The ASP.NET application, now impersonating the client, then relies on the settings in the NTFS directories and files to allow it to gain access, or not. Be sure to format the server file space as NTFS, so that access permissions can be set”.

Note that Impersonation is disabled by default and can be specified in the web.config file as shown in the code snippet given below.

or

To impersonate a particular identity, specify the following in your application’s web.config file.