NOTES
NOTES
NOTES
1. Introduction
1.1 What is .NET? 1.2 When was .NET announced? 1.3 What versions of .NET are there? 1.4 What operating systems does the .NET Framework run on? 1.5 What tools can I use to develop .NET applications? 1.6 Why did they call it .NET? 2. Terminology
o o o o o o
2.1 What is the CLI? Is it the same as the CLR? 2.2 What is IL? 2.3 What is C#? 2.4 What does 'managed' mean in the .NET context? 3. Assemblies
o o o o
3.1 What is an assembly? 3.2 How can I produce an assembly? 3.3 What is the difference between a private assembly and a shared assembly? o 3.4 How do assemblies find each other? o 3.5 How does assembly versioning work? o 3.6 How can I develop an application that automatically updates itself from the web? 4. Application Domains
o o o
4.1 What is an application domain? 4.2 How does an AppDomain get created? 4.3 Can I write my own .NET host? 5. Garbage Collection
o o o o o o o o o o
5.1 What is garbage collection? 5.2 Is it true that objects don't always get destroyed immediately when the last reference goes away? 5.3 Why doesn't the .NET runtime offer deterministic destruction? 5.4 Is the lack of deterministic destruction in .NET a problem? 5.5 Should I implement Finalize on my class? Should I implement IDisposable? 5.6 Do I have any control over the garbage collection algorithm? 5.7 How can I find out what the garbage collector is doing?
5.8 What is the lapsed listener problem? 5.9 When do I need to use GC.KeepAlive? 6. Serialization
o o
6.1 What is serialization? 6.2 Does the .NET Framework have in-built support for serialization? 6.3 I want to serialize instances of my class. Should I use XmlSerializer, SoapFormatter or BinaryFormatter? o 6.4 Can I customise the serialization process? o 6.5 Why is XmlSerializer so slow? o 6.6 Why do I get errors when I try to serialize a Hashtable? o 6.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is? o 6.8 Why am I getting an InvalidOperationException when I serialize an ArrayList? 7. Attributes
o o o
7.1 What are attributes? 7.2 Can I create my own metadata attributes? 7.3 Can I create my own context attibutes? 8. Code Access Security
o o o
8.1 What is Code Access Security (CAS)? 8.2 How does CAS work? 8.3 Who defines the CAS code groups? 8.4 How do I define my own code group? 8.5 How do I change the permission set for a code group? 8.6 Can I create my own permission set? 8.7 I'm having some trouble with CAS. How can I troubleshoot the problem? o 8.8 I can't be bothered with CAS. Can I turn it off? 9. Intermediate Language (IL)
o o o o o o o
9.1 Can I look at the IL for an assembly? 9.2 Can source code be reverse-engineered from IL? 9.3 How can I stop my code being reverse-engineered from IL? 9.4 Can I write IL programs directly? 9.5 Can I do things in IL that I can't do in C#? 10. Implications for COM
o o o o o o o o o o o
10.1 Does .NET replace COM? 10.2 Is DCOM dead? 10.3 Is COM+ dead? 10.4 Can I use COM components from .NET programs? 10.5 Can I use .NET components from COM programs? 10.6 Is ATL redundant in the .NET world?
11. Threads
11.1 How do I spawn a thread? 11.2 How do I stop a thread? 11.3 How do I use the thread pool? 11.4 How do I know when my thread pool work item has completed? 11.5 How do I prevent concurrent access to my data? 11.6 Should I use ReaderWriterLock instead of Monitor.Enter/Exit? 12. Tracing
o o o o o o
12.1 Is there built-in support for tracing/logging? 12.2 Can I redirect tracing to a file? 12.3 Can I customise the trace output? 12.4 Are there any third party logging components available? 13. Miscellaneous
o o o o
13.1 How does .NET remoting work? 13.2 How can I get at the Win32 API from a .NET program? 13.3 How do I write to the application configuration file at runtime? 13.4 What is the difference between an event and a delegate? 13.5 What size is a .NET object? 13.6 Will my .NET app run on 64-bit Windows? 13.7 What is reflection? 14. .NET 2.0
o o o o o o o
14.1 What are the new features of .NET 2.0? 14.2 What are the new 2.0 features useful for? 14.3 What's the problem with .NET generics? 14.4 What's new in the .NET 2.0 class library? 15. Resources
o o o o o o o o
15.1 Recommended books 15.2 Web sites 15.3 Blogs 15.4 Free tools
1. Introduction
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.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.
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.
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. NonMicrosoft CLI implementations include Mono and DotGNU Portable.NET.
"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.
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.
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, strongnaming is optional.
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.
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; } }
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.
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.
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.
[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.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass" error. How do I find out what the problem is?
Look at the InnerException property of the exception that is thrown to get a more specific error message.
7. Attributes
7.1 What are attributes?
There are at least two types of .NET attribute. The first type I will refer to as a metadata attribute - it allows some data to be attached to a class or method. This data becomes part of the metadata for the class, and (like other class metadata) can be accessed via reflection. An example of a metadata attribute is [serializable], which can be attached to a class and means that instances of the class can be serialized.
[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.
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 ); } }
1.4. Zone - Untrusted: Nothing 1.5. Zone - Trusted: Internet 1.6. StrongName 0024000004800000940000000602000000240000525341310004000003 000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FE F8348EBD06 F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8 F83B465E08 07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D3 8561AABF5C 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 subdivided. Also note that (somewhat counter-intuitively) a sub-group can be associated with a more permissive permission set than its parent.
Now if you run caspol -lg you will see that the new group has been added as group 1.3.1:
... 1.3. Zone - Internet: Internet 1.3.1. Site - www.mydomain.com: FullTrust ...
Note that the numeric label (1.3.1) is just a caspol invention to make the code groups easy to manipulate from the command-line. The underlying runtime never sees it.
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.
Then, to apply the permission set to a code group, do something like this:
caspol -cg 1.3 SamplePermSet
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.
Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL.
Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.
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; }; };