Tuesday, April 12, 2005

.Net FAQ Interviewers Choice

What is Microsoft.NET?

Microsoft .NET is the Microsoft strategy for connecting systems, information, and devices through Web services so people can collaborate and communicate more effectively. .NET technology is integrated throughout Microsoft products, providing the capability to quickly build

What are Web Services?


Web services aresmall, reusable applications that help computers from many different operatingsystem platforms work together by exchanging messages. Web services are basedon industry protocols that includeXML(Extensible Markup Language),

From a businessperspective, Web services are used to reenable information technology so thatit can change, move, and adapt like other aspects of a business.  They notonly connect systems, they can help connect people with the information theyneed, within the software applications they are used to using, and whereverthey happen to be.

Microsoft offersa complete range of software that helps organizations and individuals benefitfrom Web service-based connectivity. These include theMicrosoftOffice System that "consume" Web services.


This illustrationshows the relationship between the

 What are theBenefits of .NET?


.NET technologiesuse Web services to help enhance the computing experience with highlyintegrated communications and inform


NETbenefits organizations by helping them get the most out of their existingtechnology investments while creating new ways to implement powerful,cost-effective information technology that will meet future needs. .NETtechnologies and Web services can be used to integrate even the most disparatecomputing environments. .NET frees organizations from the confines ofproprietary technology, providing the flexibility and scalability that can helporganizations connect their existing IT systems and build a foundation for thenext wave of computer technology. .NET and Web services can help organizationslower operating costs by helping connect systems; increase sales by helpingemployees access the right information when and where they need it; integrateservices and applications with customers and partners; and lower the costs ofinformation technology with tools that help developers quickly create newsolutions to address business issues. 


• .NETbenefits individuals by helping provide a more personal and integratedcomputing experience. .NET-enabled computing is centered on the user–not on thefeatures of the software or hardware. The user's experience becomes verycustomizable and provides integrated data and customized interactions that workwell with a wide range of computing hardware, such as Pocket PCs, Smartphones,laptops, and other devices. The .NET-based experience enhances the mobilecomputing experience so user's can get their information regardless of theirlocation. For example, it can take place on a desktop computer, in the car on aSmartphone, or at the store on a Pocket PC.




• .NETbenefits developers by providing a tightly integrated set of tools for buildingand integrating Web services. Visual Studio .NET and the .NET Framework providecomprehensive development platforms that offer the best, fastest, and mostcost-effective way to build Web services. With Visual Studio .NET and the .NETFramework, developers can take advantage of a programming model designed from theground up for creating Web services in a highly productive, multilanguageenvironment. With scalable, high-performance execution, the .NET tools allowdevelopers to use existing skills to create a wide range of solutions that workacross a broad array of computing devices. .NET also provides a foundation forbuilding Service Oriented Architectures (SOA).



What areService Oriented Architectures (SOA)?

SOAdescribes an information technology architecture that enables distributedcomputing environments with many different types of computing platforms andapplications. Web services are one of the technologies that help make SOAspossible. As a concept, SOA has been around since the 1980s, but many early ITtechnologies failed to achieve the goal of linking different types ofapplications and systems. By making early investments with .NET, Microsoft hashelped provide the building blocks that today are putting many enterprisecustomers on the path to successfully implementing SOAs. With SOAs, companiescan benefit from the unimpeded flow of information that is the hallmark ofconnected systems



What areWeb Services Enhancements for Microsoft .NET (WSE)?

WSE is anadd-on to Microsoft Visual Studio .NET and the Microsoft .NET Framework thathelps developers build greater security features into Web services using thelatest Web services protocol specifications and standards. With WSE 2.0developers can create security-enhanced connected systems that help improvebusiness processes within–and beyond–corporate trust boundaries and create newrevenue-generating opportunities.



What is aSmart Client?

Smartclients are client applications that consume Web services and reside on userhardware such as desktop PCs, laptops, Pocket PCs, and Smartphones. They areeasily deployed and managed and provide an adaptive, responsive, and richinteractive experience by taking advantage of the computing resources on thedevice and intelligently connecting to distributed data sources.



What is.NET Passport?

.NETPassport is a Web-based service that is designed to make signing in to Websites fast and easy. Passport enables participating sites to authenticate auser with a single set of sign-in credentials, alleviating the need for usersto remember numerous passwords and user names.


What arethe Current Microsoft Products and Technologies That Use .NET?

Microsoft.NET provides everything that is needed to develop and deploy a Webservice-based IT architecture: servers to host Web services; development toolsto create Web services; applications to use them; and a network of more than35,000 Microsoft partners to help organizations deploy and manage them. .NETtechnologies are supported throughout the family of Microsoft products,including the Windows Server System, the Windows XP desktop operating system,and the Microsoft Office System. And .NET technologies will play an even largerrole in future versions of Microsoft products.


Who isUsing .NET?

Organizationsworldwide are implementing .NET technologies and Web services to createconnected businesses and to help individuals communicate and collaborate moreeffectively. For example, Honeywell, GlaxoSmithKline, Sony, Dollar Rent A Car,Farmers Insurance, and the United States Postal Service are just a few of thewell-known names that are using .NET. To read more about .NET technology in usetoday, visit the Microsoft .NET Case Study site.


How Do IFind a Microsoft Partner to Help Me Connect My Organization Using .NET?

MicrosoftCertified Partners are independent companies that can provide you with thehighest levels of technical expertise, strategic thinking, and hands-on skills.Microsoft Certified Partners encompass a broad range of expertise and vendoraffiliations. Their real-world perspective can help you prioritize and effectivelydeliver your technology solutions. Finda partner in your area, here.


1. Introduction

1.1 What is .NET?

.NET is a general-purpose software developmentplatform, similar to Java. At its core is a virtual machine that turnsintermediate language (IL) into machine code. High-level language compilers forC#, VB.NET and C++ are provided to turn source code into IL. C# is a newprogramming language, very similar to Java. An extensive class library isincluded, featuring all the functionality one might expect from a contemporydevelopment platform - windows GUI development (Windows Forms), database access(ADO.NET), web development (ASP.NET), web services, XML etc.

See also Microsoft'sMono project has a version of the .NET Framework thatruns on Linux.

1.5 What tools can I use to develop.NET applications?

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

·        TheMicrosoft Visual C# .NET Standard2003 is a cheap (around $100) version of Visual Studio limited toone language and also with limited wizard support. For example, there's nowizard support for class libraries or custom UI controls. Useful for beginnersto learn with, or for savvy developers who can work around the deficiencies inthe supplied wizards. As well as C#, there areVB.NET andC++ versions.

·        Microsoft Visual Studio.NETProfessional 2003. If you have a license for Visual Studio 6.0, youcan get theupgrade. You can alsoupgrade from VS.NET2002 for a token $30. Visual Studio.NET includes support for all the MSlanguages (C#, C++, VB.NET) and has extensive wizard support.

At the topend of the price spectrum are the Visual Studio.NET 2003Enterprise andEnterprise Architecteditions. These offer extra features such as Visual Sourcesafe (versioncontrol), and performance and analysis tools. Check out the Visual Studio.NETFeature Comparison at.NET Compact Framework for mobile devices.Non-Microsoft CLI implementations includeMono and

Substitute 'Java' for 'C#' in the quote above, andyou'll see that the statement still works pretty well :-).

If you are a C++ programmer, you might like to checkout my

Alternatively you can compile your source intomodules, and then combine the modules into an assembly using the assemblylinker (al.exe). For the C# compiler, the /target:module switch is used togenerate a module instead of an assembly.

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

·        Locationand visibility: A private assembly is normally usedby a single application, and is stored in the application's directory, or asub-directory beneath. A shared assembly is normally stored in the globalassembly cache, which is a repository of assemblies maintained by the .NETruntime. Shared assemblies are usually libraries of code which manyapplications will find useful, e.g. the .NET framework classes.

·        Versioning:The runtime enforces versioning constraints only on shared assemblies, not onprivate assemblies.

3.4 How do assemblies find eachother?

By searching directory paths. There are severalfactors which can affect the path (such as the AppDomain host, and applicationconfiguration files), but for private assemblies the search path is normallythe application's directory and its sub-directories. For shared assemblies, thesearch path is normally same as the private assembly path plus the sharedassembly cache.

3.5 How does assembly versioningwork?

Each assembly has a version number called thecompatibility version. Also each reference to an assembly (from anotherassembly) includes both the name and version of the referenced assembly.

The version number has four numeric parts (e.g. Assemblies with either of the first two parts different are normallyviewed as incompatible. If the first two parts are the same, but the third isdifferent, the assemblies are deemed as 'maybe compatible'. If only the fourthpart is different, the assemblies are deemed compatible. However, this is justthe default guideline - it is the version policy that decides to what extentthese rules are enforced. The version policy can be specified via theapplication configuration file.

Remember:versioning is only applied to shared assemblies, not private assemblies.

3.6 How can I develop an applicationthat automatically updates itself from the web?

For .NET 1.x, use theUpdater Application Block.For .NET 2.x, useClickOnce.

4. Application Domains

4.1 What is an application domain?

An AppDomain can be thought of as a lightweightprocess. Multiple AppDomains can exist inside a Win32 process. The primarypurpose of the AppDomain is to isolate applications from each other, and so itis particularly useful in hosting scenarios such as ASP.NET. An AppDomain canbe destroyed by the host without affecting other AppDomains in the process.

Win32 processes provide isolation by having distinctmemory address spaces. This is effective, but expensive. The .NET runtimeenforces AppDomain isolation by keeping control over the use of memory - allmemory in the AppDomain is managed by the .NET runtime, so the runtime canensure that AppDomains do not access each other's memory.

One non-obvious use of AppDomains is for unloadingtypes. Currently the only way to unload a .NET type is to destroy the AppDomainit is loaded into. This is particularly useful if you create and destroy typeson-the-fly via reflection.

Microsoft have an  

  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 atthe source for thelengthy analysis ofthe problem. Chris Sells'response to Brian'sposting is here.

5.3 Why doesn't the .NET runtimeoffer deterministic destruction?

Because of the garbage collection algorithm. The .NETgarbage collector works by periodically running through a list of all theobjects that are currently being referenced by an application. All the objectsthat it doesn't find during this search are ready to be destroyed and thememory reclaimed. The implication of this algorithm is that the runtime doesn'tget notified immediately when the final reference on an object goes away - itonly finds out during the next 'sweep' of the heap.

Futhermore, this type of algorithm works best byperforming the garbage collection sweep as rarely as possible. Normally heapexhaustion is the trigger for a collection sweep.

5.4 Is the lack of deterministicdestruction 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. databaselocks), you need to provide some way to tell the object to release the resourcewhen it is done. Microsoft recommend that you provide a method called Dispose()for this purpose. However, this causes problems for distributed objects - in adistributed system who calls the Dispose() method? Some form ofreference-counting or ownership-management mechanism is needed to handledistributed objects - unfortunately the runtime offers no help with this.

5.5 Should I implement Finalize onmy class? Should I implement IDisposable?

This issue is a little more complex than it firstappears. There are really two categories of class that require deterministicdestruction - the first category manipulate unmanaged types directly (generallyvia an IntPtr representing an OS handle), whereas the second categorymanipulatemanaged types that require deterministic destruction. Anexample of the first category is a class with an IntPtr member representing anOS file handle. An example of the second category is a class with aSystem.IO.FileStream member.

For the first category, it makes sense to implementIDisposableand override Finalize. This allows the object user to 'dothe right thing' by calling Dispose, but also provides a fallback of freeingthe unmanaged resource in the Finalizer, should the calling code fail in itsduty. However this logic does not apply to the second category of class, withonly managed resources. In this case implementing Finalize is pointless, asmanaged member objects cannot be accessed in the Finalizer. This is becausethere is no guarantee about the ordering of Finalizer execution. So only theDispose method should be implemented. (If you think about it, it doesn't reallymake sense to call Dispose on member objects from a Finalizer anyway, as themember object's Finalizer will do the required cleanup anyway.)

For classes that need to implement IDisposableandoverride Finalize, see Microsoft'sdocumented pattern.

Note thatsome developers argue that implementing a Finalizer is always a bad idea, as ithides a bug in your code (i.e. the lack of a Dispose call). A less radicalapproach is to implement Finalize but include a Debug.Assert at the start, thussignalling the problem in developer builds but allowing the cleanup to occur inrelease builds.

5.6 Do I have any control over thegarbage collection algorithm?

A little. For example the System.GC class exposes aCollect method, which forces the garbage collector to collect all unreferencedobjects immediately.

Also there is agcConcurrent setting that canbe specified via the application configuration file. This specifies whether ornot the garbage collector performs some of its collection activities on aseparate thread. The setting only applies on multi-processor machines, anddefaults to true.

5.7 How can I find out what thegarbage collector is doing?

Lots of interesting statistics are exported from the.NET runtime via the '.NET CLR xxx' performance counters. Use PerformanceMonitor to view them.

5.8 What is the lapsed listenerproblem?

The lapsed listener problem is one of the primarycauses of leaks in .NET applications. It occurs when a subscriber (or'listener') signs up for a publisher's event, but fails to unsubscribe. Thefailure to unsubscribe means that the publisher maintains a reference to thesubscriber as long as the publisher is alive. For some publishers, this may bethe duration of the application.

This situation causes two problems. The obviousproblem is the leakage of the subscriber object. The other problem is theperformance degredation due to the publisher sending redundant notifications to'zombie' subscribers.

There are at least a couple of solutions to theproblem. The simplest is to make sure the subscriber is unsubscribed from thepublisher, typically by adding an Unsubscribe() method to the subscriber.Another solution, documentedhere by Shawn VanNess, is to change the publisher to use weak references in its subscriber list.

5.9 When do I need to useGC.KeepAlive?

It's very unintuitive, but the runtime can decide thatan object is garbage much sooner than you expect. More specifically, an objectcan become garbage while a method is executing on the object, which is contraryto most developers' expectations. Chris Brumme

 public static extern boolCloseHandle(IntPtr hObject);



 public static extern boolSetEvent(IntPtr hEvent);



class EventUser


 public EventUser()


  hEvent = Win32.CreateEvent(IntPtr.Zero, false, false, null );





  Win32.CloseHandle( hEvent );




 public void UseEvent()


  UseEventInStatic( this.hEvent );



 static void UseEventInStatic( IntPtrhEvent )



  bool bSuccess = Win32.SetEvent(hEvent );

  Console.WriteLine( "SetEvent" + (bSuccess ? "succeeded" : "FAILED!") );



 IntPtr hEvent;



class App


 static void Main(string[] args)


  EventUser eventUser = newEventUser();




If you runthis code, it'll probably work fine, and you'll get the following output:

SetEvent succeeded

EventDemo finalized

However, ifyou uncomment the GC.Collect() call in the UseEventInStatic() method, you'llget this output:

EventDemo finalized

SetEvent FAILED!

(Note thatyou need to use a release build to reproduce this problem.)

So what'shappening here? Well, at the point where UseEvent() calls UseEventInStatic(), acopy is taken of the hEvent field, and there are no further references to theEventUser 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 thecollection won't happen immediately, so you'll get away with it, but sooner orlater a collection will occur at the wrong time, and your app will fail.

A solutionto this problem is to add a call to GC.KeepAlive(this) to the end of theUseEvent method, as

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 contextattibutes?

Yes. Take a look at Peter Drayton'sReflector does a verygood job of turning IL into C# or VB.NET.

9.3 How can I stop my code beingreverse-engineered from IL?

You can buy an IL obfuscation tool. These tools workby 'optimising' the IL in such a way that reverse-engineering becomes much moredifficult.

Of course if you are writing web services thenreverse-engineering is not a problem as clients do not have access to your IL.

9.4 Can I write IL programsdirectly?

Yes.Peter Drayton posted this simple example to theDOTNET mailing list:

.assembly MyAssembly {}

.class MyApp {

  .method static void Main() {


 ldstr  "Hello, IL!"

 callvoid System.Console::WriteLine(class System.Object)




Just putthis into a file called hello.il, and then run ilasm hello.il. An exe assemblywill be generated.

9.5 Can I do things in IL that I can'tdo in C#?

Yes. A couple of simple examples are that you canthrow exceptions that are not derived from System.Exception, and you can havenon-zero-based arrays.

10. Implications for COM

10.1 Does .NET replace COM?

This subject causes a lot of controversy, as you'llsee if you read the mailing list archives. Take a look at the following twothreads:


The bottomline is that .NET has its own mechanisms for type interaction, and they don'tuse COM. No IUnknown, no IDL, no typelibs, no registry-based activation. Thisis mostly good, as a lot of COM was ugly. Generally speaking, .NET allows youto package and use components in a similar way to COM, but makes the wholething a bit easier.

10.2 Is DCOM dead?

Pretty much, for .NET developers. The .NET Frameworkhas a new remoting model which is not based on DCOM. DCOM was pretty much deadanyway, once firewalls became widespread and Microsoft gotSOAP fever. Of courseDCOM will still be used in interop scenarios.

10.3 Is COM+ dead?

Not immediately. The approach for .NET 1.0 was toprovide access to the existing COM+ services (through an interop layer) ratherthan replace the services with native .NET ones. Various tools and attributeswere provided to make this as painless as possible. Over time it is expectedthat interop will become more seamless - this may mean that some servicesbecome a core part of the CLR, and/or it may mean that some services will berewritten as managed code which runs on top of the CLR.

For more on this topic, search for postings by JoeLong in the archives - Joe is the MS group manager for COM+. Start with thismessage:


10.4 Can I use COM components from.NET programs?

Yes. COM components are accessed from the .NET runtimevia a Runtime Callable Wrapper (RCW). This wrapper turns the COM interfacesexposed by the COM component into .NET-compatible interfaces. For oleautomationinterfaces, the RCW can be generated automatically from a type library. Fornon-oleautomation interfaces, it may be necessary to develop a custom RCW whichmanually 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";





 helpstring("ICppName Interface"),





interface ICppName : IUnknown


 [helpstring("method SetName")] HRESULT SetName([in] BSTRname);

 [helpstring("method GetName")] HRESULT GetName([out,retval]BSTR *pName );






 helpstring("cppcomserver 1.0 Type Library")








  helpstring("CppName Class")


 coclass CppName


  [default] interface ICppName;



When you've built the component, you should get atypelibrary. 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;



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 theDLL we previously generated from the typelibrary using TLBIMP. You should nowbe able to run csharpcomclient.exe, and get the following output on theconsole:

Name is bob

10.5 Can I use .NET components fromCOM programs?

Yes. .NET components are accessed from COM via a COMCallable Wrapper (CCW). This is similar to a RCW (see previous question), butworks in the opposite direction. Again, if the wrapper cannot be automaticallygenerated by the .NET development tools, or if the automatic behaviour is notdesirable, a custom CCW can be developed. Also, for COM to 'see' the .NETcomponent, the .NET component must be registered in the registry.

Here's a simple example. Create a C# file calledtestcomserver.cs and put the following in it:

using System;

using System.Runtime.InteropServices;


namespace AndyMc



 public class CSharpCOMServer


  public CSharpCOMServer() {}

  public void SetName( string name ) { m_name = name; }

  public string GetName() { return m_name; } 

  private string m_name;



Then compile the .cs file as follows:

csc/target:library testcomserver.cs

You should get a dll, which you register like this:

regasm testcomserver.dll /tlb:testcomserver.tlb /codebase

Now you need to create a client to test your .NET COMcomponent. VBScript will do - put the following in a file called comclient.vbs:


SetdotNetObj = 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 displayedwith the text "Name is bob".

An alternative to the approach above it to use the  

 public static extern int MessageBox(int hWnd, String strMessage, StringstrCaption, uint uiType);

 public static void Main()


  MessageBox( 0, "Hello, this is PInvoke in operation!",".NET", 0 );



post by JulienCouvreur for more discussion.

11.5 What size is a .NET object?

Each instance of a reference type has two fieldsmaintained by the runtime - a method table pointer and a sync block. These are4 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 theoverall size of the object. So, for example, instances of the following classare 12 bytes each:

class MyInt



 private int x;


However, note that with the current implementation ofthe CLR there seems to be a minimum object size of 12 bytes, even for classeswith no data (e.g. System.Object).

Values types have no equivalent overhead.

12. .NET 2.0

12.1 What are the new features of.NET 2.0?

Generics, anonymous methods, partial classes,iterators, property visibility (separate visibility for get and set) and staticclasses. Seehttp://www.mindview.net/WebLog/log-0050
Ian Griffiths:


13.1.2 How do I stop a thread?

There are several options. First, youcan use your own communication mechanism to tell the ThreadStart method tofinish. Alternatively the Thread class has in-built support for instructing thethread to stop. The two principle methods are Thread.Interrupt() andThread.Abort(). The former will cause a ThreadInterruptedException to be thrownon 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 nolonger doing any useful work. In contrast, Thread.Abort() throws aThreadAbortException regardless of what the thread is doing. Furthermore, theThreadAbortException cannot normally be caught (though the ThreadStart'sfinally method will be executed). Thread.Abort() is a heavy-handed mechanismwhich should not normally be required.

13.1.3 How do I use the thread pool?

By passing an instance of a WaitCallbackdelegate 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 tobe executed



 // DoWork is executed on a thread from the thread pool.

 static void DoWork( object state )


  Console.WriteLine( state );



13.1.4 How do I know when my threadpool work item has completed?

There is no way to query the threadpool for this information. You must put code into the WaitCallback method tosignal that it has completed. Events are useful for this.

13.1.5 How do I prevent concurrentaccess to my data?

Each object has a concurrency lock(critical section) associated with it. The System.Threading.Monitor.Enter/Exitmethods are used to acquire and release this lock. For example, instances ofthe following class only allow one thread at a time to enter method f():

class C


 public void f()













C# has a 'lock' keyword whichprovides a convenient shorthand for the code above:

class C


 public void f()








Note that callingMonitor.Enter(myObject) does NOT mean that all access to myObject isserialized. It means that the synchronisation lock associated with myObject hasbeen 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 classesabove:

class C


 public void f()


  lock( m_object )






 private m_object = new object();


Actually, it could be argued thatthis version of the code is superior, as the lock is totally encapsulatedwithin the class, and not accessible to the user of the object.

13.2 Tracing

13.2.1 Is there built-in support fortracing/logging?

Yes, in the System.Diagnosticsnamespace. 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 Debugclass only works in builds that have the DEBUG symbol defined, whereas tracingfrom the Trace class only works in builds that have the TRACE symbol defined.Typically this means that you should use System.Diagnostics.Trace.WriteLine fortracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLinefor tracing that you want to work only in debug builds.

13.2.2 Can I redirect tracing to afile?

Yes. The Debug and Trace classes bothhave a Listeners property, which is a collection of sinks that receive thetracing that you send via Debug.WriteLine and Trace.WriteLine respectively. Bydefault the Listeners collection contains a single sink, which is an instanceof the DefaultTraceListener class. This sends output to the Win32OutputDebugString() function and also the System.Diagnostics.Debugger.Log()method. This is useful when debugging, but if you're trying to trace a problemat 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 theTextWriterTraceListener class to redirect Trace output to a file:


FileStream fs = new FileStream( @"c:\log.txt",FileMode.Create, FileAccess.Write );

Trace.Listeners.Add( new TextWriterTraceListener( fs ) );


Trace.WriteLine( @"This will be writen toc:\log.txt!" );


Note the use ofTrace.Listeners.Clear() to remove the default listener. If you don't do this,the output will go to the fileand OutputDebugString(). Typically thisis not what you want, because OutputDebugString() imposes a big performancehit.

13.2.3 Can I customise the traceoutput?

Yes. You can write your ownTraceListener-derived class, and direct all output through it. Here's a simpleexample, which derives from TextWriterTraceListener (and therefore has in-builtsupport for writing to files, as shown above) and adds timing information andthe 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,


    s );



 protected int m_startTickCount = Environment.TickCount;


(Note that this implementation is notcomplete - the TraceListener.Write method is not overridden for example.)

The beauty of this approach is thatwhen an instance of MyListener is added to the Trace.Listeners collection, allcalls to Trace.WriteLine() go through MyListener, including calls made byreferenced assemblies that know nothing about the MyListener class.

13.2.4 Are there any third partylogging components available?

VB edition of thebook.

·        Essential .NET Volume 1, TheCommon Language Runtime - Don Box
A superb book, which I recommend to anyone who already has some .NETdevelopment experience, and wants to get a deeper understanding of CLRfundamentals. It's clear that Box has deeply researched the topics and thencarefully constructed a coherent story around his findings. It's rare to findsuch craft in a.NET text.

·        C# and the .NET Platform, 2nd Edition- Andrew Troelsen
Regarded by many as the best all round C#/.NET book. Wide coverage includingWindows Forms, COM interop, ADO.NET, ASP.NET etc. Troelsen also has a respectedVB.NET book calledVisual Basic .NET and the .NETPlatform: An Advanced Guide.

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

·        Windows Forms Programming in C# -Chris Sells
I haven't read this myself yet, but anything Sells writes is usually worthreading.

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

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

·        .NET and COM - The CompleteInteroperability Guide - Adam Nathan
Don't be put off by the size - this book is very easy to digest thanks to thesuperb writing style. The bible of .NET/COM interop.

·        Advanced .NET Remoting - IngoRammer
Widely recommended.

14.2 Web sites

·        TheMicrosoft .NET homepage is athttp://www.microsoft.com/net/.Microsoft also hostGOTDOTNET.

·        ChrisSells has a great set of.NET links.

·        microsoft.public.dotnet.*newsgroups

·        SyncfusionWinforms FAQ.

·        IngoRammer'sC# FAQ for C++ Programmers.

14.3 Blogs

The following Weblogs ('blogs') have regular .NETcontent:

·        Gwyn Cole: Co-author of Developing WMI solutions.

·        Don Box

·        Simon Fell: Developer of PocketSOAP.


Conceptual Questions


What is the .NETFramework?

The Microsoft .NET Framework is a platform for building,deploying, and running Web Services and applications. It provides a highlyproductive, standards-based, multi-language environment for integratingexisting investments with next-generation applications and services as well asthe agility to solve the challenges of deployment and operation of Internet-scaleapplications. The .NET Framework consists of three main parts: the commonlanguage runtime, a hierarchical set of unified class libraries, and acomponentized version of Active Server Pages called ASP.NET.




Runtime TechnicalQuestions



What is the common language runtime (CLR)?

The common language runtime is the execution engine for .NETFramework applications.


It provides a number of services, including the following:


Code management (loading and execution)

Application memory isolation

Verification of type safety

Conversion of IL to native code

Access to metadata (enhanced type information)

Managing memory for managed objects

Enforcement of code access security

Exception handling, including cross-language exceptions

Interoperation between managed code, COM objects, andpre-existing DLLs (unmanaged code and data)

Automation of object layout

Support for developer services (profiling, debugging, and soon)



What is the commontype system (CTS)?

The common type system is a rich type system, built into thecommon language runtime, that supports the types and operations found in mostprogramming languages. The common type system supports the completeimplementation of a wide range of programming languages.






What is the CommonLanguage Specification (CLS)?

The Common Language Specification is a set of constructs andconstraints that serves as a guide for library writers and compiler writers. Itallows libraries to be fully usable from any language supporting the CLS, andfor those languages to integrate with each other. The Common LanguageSpecification is a subset of the common type system. The Common LanguageSpecification is also important to application developers who are writing codethat will be used by other developers. When developers design publiclyaccessible APIs following the rules of the CLS, those APIs are easily used fromall other programming languages that target the common language runtime.




What is the MicrosoftIntermediate Language (MSIL)?

MSIL is the CPU-independent instruction set into which .NETFramework programs are compiled. It contains instructions for loading, storing,initializing, and calling methods on objects.


Combined with metadata and the common type system, MSILallows for true cross-language integration.


Prior to execution, MSIL is converted to machine code. It isnot interpreted.




What is managed codeand managed data?


Managed code is code that is written to target the servicesof the common language runtime (see What is the Common Language Runtime?). Inorder to target these services, the code must provide a minimum level ofinformation (metadata) to the runtime. All C#, Visual Basic .NET, and JScript.NET code is managed by default. Visual Studio .NET C++ code is not managed bydefault, but the compiler can produce managed code by specifying a command-lineswitch (/CLR).


Closely related to managed code is managed data—data that isallocated and de-allocated by the common language runtime's garbage collector.C#, Visual Basic, and JScript .NET data is managed by default. C# data can,however, be marked as unmanaged through the use of special keywords. VisualStudio .NET C++ data is unmanaged by default (even when using the /CLR switch),but when using Managed Extensions for C++, a class can be marked as managed byusing the __gc keyword. As the name suggests, this means that the memory forinstances of the class is managed by the garbage collector. In addition, theclass becomes a full participating member of the .NET Framework community, withthe benefits and restrictions that brings. An example of a benefit is properinteroperability with classes written in other languages (for example, amanaged C++ class can inherit from a Visual Basic class). An example of arestriction is that a managed class can only inherit from one base class.






What is an assembly?

An assembly is the primary building block of a .NETFramework application. It is a collection of functionality that is built,versioned, and deployed as a single implementation unit (as one or more files).All managed types and resources are marked either as accessible only withintheir implementation unit, or as accessible by code outside that unit.


Assemblies are self-describing by means of their manifest,which is an integral part of every assembly. The manifest:


Establishes the assembly identity (in the form of a textname), version, culture, and digital signature (if the assembly is to be sharedacross applications).

Defines what files (by name and file hash) make up theassembly implementation.

Specifies the types and resources that make up the assembly,including which are exported from the assembly.

Itemizes the compile-time dependencies on other assemblies.

Specifies the set of permissions required for the assemblyto run properly.

This information is used at run time to resolve references,enforce version binding policy, and validate the integrity of loadedassemblies. The runtime can determine and locate the assembly for any runningobject, since every type is loaded in the context of an assembly. Assembliesare also the unit at which code access security permissions are applied. Theidentity evidence for each assembly is considered separately when determiningwhat permissions to grant the code it contains.


The self-describing nature of assemblies also helps makeszero-impact install and XCOPY deployment feasible.




What are privateassemblies and shared assemblies?

A private assembly is used only by a single application, andis stored in that application's install directory (or a subdirectory therein).A shared assembly is one that can be referenced by more than one application.In order to share an assembly, the assembly must be explicitly built for thispurpose by giving it a cryptographically strong name (referred to as a strongname). By contrast, a private assembly name need only be unique within theapplication that uses it.


By making a distinction between private and sharedassemblies, we introduce the notion of sharing as an explicit decision. Simplyby deploying private assemblies to an application directory, you can guaranteethat that application will run only with the bits it was built and deployedwith. References to private assemblies will only be resolved locally to theprivate application directory.


There are several reasons you may elect to build and useshared assemblies, such as the ability to express version policy. The fact thatshared assemblies have a cryptographically strong name means that only theauthor of the assembly has the key to produce a new version of that assembly.Thus, if you make a policy statement that says you want to accept a new versionof an assembly, you can have some confidence that version updates will becontrolled and verified by the author. Otherwise, you don't have to acceptthem.


For locally installed applications, a shared assembly istypically explicitly installed into the global assembly cache (a local cache ofassemblies maintained by the .NET Framework). Key to the version managementfeatures of the .NET Framework is that downloaded code does not affect theexecution of locally installed applications. Downloaded code is put in aspecial download cache and is not globally available on the machine even ifsome of the downloaded components are built as shared assemblies.


The classes that ship with the .NET Framework are all builtas shared assemblies.




If I want to build a shared assembly, does that require theoverhead of signing and managing key pairs?


Building a shared assembly does involve working withcryptographic keys. Only the public key is strictly needed when the assembly isbeing built. Compilers targeting the .NET Framework provide command lineoptions (or use custom attributes) for supplying the public key when buildingthe assembly. It is common to keep a copy of a common public key in a sourcedatabase and point build scripts to this key. Before the assembly is shipped,the assembly must be fully signed with the corresponding private key. This isdone using an SDK tool called SN.exe (Strong Name).


Strong name signing does not involve certificates likeAuthenticode does. There are no third party organizations involved, no fees topay, and no certificate chains. In addition, the overhead for verifying astrong name is much less than it is for Authenticode. However, strong names donot make any statements about trusting a particular publisher. Strong namesallow you to ensure that the contents of a given assembly haven't been tamperedwith, and that the assembly loaded on your behalf at run time comes from thesame publisher as the one you developed against. But it makes no statementabout whether you can trust the identity of that publisher.




What is thedifference between a namespace and an assembly name?

A namespace is a logical naming scheme for types in which asimple type name, such as MyType, is preceded with a dot-separated hierarchicalname. Such a naming scheme is completely under the control of the developer.For example, types MyCompany.FileAccess.A and MyCompany.FileAccess.B might belogically expected to have functionality related to file access. The .NETFramework uses a hierarchical naming scheme for grouping types into logicalcategories of related functionality, such as the Microsoft® ASP.NET applicationframework, or remoting functionality. Design tools can make use of namespacesto make it easier for developers to browse and reference types in their code.The concept of a namespace is not related to that of an assembly. A singleassembly may contain types whose hierarchical names have different namespaceroots, and a logical namespace root may span multiple assemblies. In the .NETFramework, a namespace is a logical design-time naming convenience, whereas anassembly establishes the name scope for types at run time.




Application Deployment and Isolation


What options areavailable to deploy my .NET applications?

The .NET Framework simplifies deployment by makingzero-impact install and XCOPY deployment of applications feasible. Because allrequests are resolved first to the private application directory, simplycopying an application's directory files to disk is all that is needed to runthe application. No registration is required.


This scenario is particularly compelling for Webapplications, Web Services, and self-contained desktop applications. However,there are scenarios where XCOPY is not sufficient as a distribution mechanism.An example is when the application has little private code and relies on theavailability of shared assemblies, or when the application is not locallyinstalled (but rather downloaded on demand). For these cases, the .NETFramework provides extensive code download services and integration with theWindows Installer. The code download support provided by the .NET Frameworkoffers several advantages over current platforms, including incrementaldownload, code access security (no more Authenticode dialogs), and applicationisolation (code downloaded on behalf of one application doesn't affect otherapplications). The Windows Installer is another powerful deployment mechanismavailable to .NET applications. All of the features of Windows Installer,including publishing, advertisement, and application repair will be availableto .NET applications in Windows Installer 2.0.




I've written an assemblythat I want to use in more than one application. Where do I deploy it?

Assemblies that are to be used by multiple applications (forexample, shared assemblies) are deployed to the global assembly cache. In theprerelease and Beta builds, use the /i option to the GACUtil SDK tool toinstall an assembly into the cache:


gacutil /i myDll.dll

Windows Installer 2.0, which ships with Windows XP andVisual Studio .NET will be able to install assemblies into the global assemblycache.




How can I see what assemblies are installed in the globalassembly cache?

The .NET Framework ships with a Windows shell extension forviewing the assembly cache. Navigating to % windir%\assembly with the WindowsExplorer activates the viewer.




What is anapplication domain?

An application domain (often AppDomain) is a virtual processthat serves to isolate an application. All objects created within the sameapplication scope (in other words, anywhere along the sequence of objectactivations beginning with the application entry point) are created within thesame application domain. Multiple application domains can exist in a singleoperating system process, making them a lightweight means of applicationisolation.


An OS process provides isolation by having a distinct memoryaddress space. While this is effective, it is also expensive, and does notscale to the numbers required for large web servers. The Common LanguageRuntime, on the other hand, enforces application isolation by managing thememory use of code running within the application domain. This ensures that itdoes not access memory outside the boundaries of the domain. It is important tonote that only type-safe code can be managed in this way (the runtime cannotguarantee isolation when unsafe code is loaded in an application domain).




Garbage Collection

What is garbagecollection?

Garbage collection is a mechanism that allows the computerto detect when an object can no longer be accessed. It then automaticallyreleases the memory used by that object (as well as calling a clean-up routine,called a "finalizer," which is written by the user). Some garbagecollectors, like the one used by .NET, compact memory and therefore decreaseyour program's working set.




How doesnon-deterministic garbage collection affect my code?

For most programmers, having a garbage collector (and usinggarbage collected objects) means that you never have to worry aboutdeallocating memory, or reference counting objects, even if you usesophisticated data structures. It does require some changes in coding style,however, if you typically deallocate system resources (file handles, locks, andso forth) in the same block of code that releases the memory for an object.With a garbage collected object you should provide a method that releases thesystem resources deterministically (that is, under your program control) andlet the garbage collector release the memory when it compacts the working set.




Can I avoid using thegarbage collected heap?

All languages that target the runtime allow you to allocateclass objects from the garbage-collected heap. This brings benefits in terms offast allocation, and avoids the need for programmers to work out when theyshould explicitly 'free' each object.


The CLR also provides what are called ValueTypes—these arelike classes, except that ValueType objects are allocated on the runtime stack(rather than the heap), and therefore reclaimed automatically when your codeexits the procedure in which they are defined. This is how "structs"in C# operate.


Managed Extensions to C++ lets you choose where classobjects are allocated. If declared as managed Classes, with the __gc keyword,then they are allocated from the garbage-collected heap. If they don't includethe __gc keyword, they behave like regular C++ objects, allocated from the C++heap, and freed explicitly with the "free" method.


For additional information about Garbage Collection see:


Garbage Collection: Automatic Memory Management in theMicrosoft .NET Framework

Garbage Collection, Part 2: Automatic Memory Management inthe Microsoft .NET Framework





How do in-process andcross-process communication work in the Common Language Runtime?


There are two aspects to in-process communication: betweencontexts within a single application domain, or across application domains.Between contexts in the same application domain, proxies are used as aninterception mechanism. No marshaling/serialization is involved. When crossingapplication domains, we do marshaling/serialization using the runtime binaryprotocol.


Cross-process communication uses a pluggable channel andformatter protocol, each suited to a specific purpose.


If the developer specifies an endpoint using the toolsoapsuds.exe to generate a metadata proxy, HTTP channel with SOAP formatter isthe default.

If a developer is doing explicit remoting in the managedworld, it is necessary to be explicit about what channel and formatter to use.This may be expressed administratively, through configuration files, or withAPI calls to load specific channels. Options are:

HTTP channel w/ SOAP formatter (HTTP works well on theInternet, or anytime traffic must travel through firewalls)


TCP channel w/ binary formatter (TCP is a higher performanceoption for local-area networks (LANs))


When making transitions between managed and unmanaged code,the COM infrastructure (specifically, DCOM) is used for remoting. In interimreleases of the CLR, this applies also to serviced components (components thatuse COM+ services). Upon final release, it should be possible to configure anyremotable component.


Distributed garbage collection of objects is managed by asystem called "leased based lifetime." Each object has a lease time,and when that time expires, the object is disconnected from the remotinginfrastructure of the CLR. Objects have a default renew time-the lease isrenewed when a successful call is made from the client to the object. Theclient can also explicitly renew the lease.






Can I use COM objectsfrom a .NET Framework program?

Yes. Any COM component you have deployed today can be usedfrom managed code, and in common cases the adaptation is totally automatic.


Specifically, COM components are accessed from the .NETFramework by use of a runtime callable wrapper (RCW). This wrapper turns theCOM interfaces exposed by the COM component into .NET Framework-compatibleinterfaces. For OLE automation interfaces, the RCW can be generatedautomatically from a type library. For non-OLE automation interfaces, adeveloper may write a custom RCW and manually map the types exposed by the COMinterface to .NET Framework-compatible types.




Can .NET Frameworkcomponents be used from a COM program?

Yes. Managed types you build today can be made accessiblefrom COM, and in the common case the configuration is totally automatic. Thereare certain new features of the managed development environment that are notaccessible from COM. For example, static methods and parameterized constructorscannot be used from COM. In general, it is a good idea to decide in advance whothe intended user of a given type will be. If the type is to be used from COM,you may be restricted to using those features that are COM accessible.


Depending on the language used to write the managed type, itmay or may not be visible by default.


Specifically, .NET Framework components are accessed fromCOM by using a COM callable wrapper (CCW). This is similar to an RCW (seeprevious question), but works in the opposite direction. Again, if the .NETFramework development tools cannot automatically generate the wrapper, or ifthe automatic behavior is not what you want, a custom CCW can be developed.




Can I use the Win32API from a .NET Framework program?

Yes. Using platform invoke, .NET Framework programs canaccess native code libraries by means of static DLL entry points.


Here is an example of C# calling the Win32 MessageBoxfunction:


using System;

using System.Runtime.InteropServices;


class MainApp


[DllImport("user32.dll", EntryPoint="MessageBox")]

public staticextern int MessageBox(int hWnd, String strMessage, String strCaption, uintuiType);


public staticvoid Main()


 MessageBox(0, "Hello, this is PInvoke in operation!", ".NET", 0 );







What do I have to do to make my code work with the securitysystem?

Usually, not a thing—most applications will run safely andwill not be exploitable by malicious attacks. By simply using the standardclass libraries to access resources (like files) or perform protectedoperations (such as a reflection on private members of a type), security willbe enforced by these libraries. The one simple thing application developers maywant to do is include a permission request (a form of declarative security) tolimit the permissions their code may receive (to only those it requires). Thisalso ensures that if the code is allowed to run, it will do so with all thepermissions it needs.


Only developers writing new base class libraries that exposenew kinds of resources need to work directly with the security system. Insteadof all code being a potential security risk, code access security constrainsthis to a very small bit of code that explicitly overrides the security system.




Why does my code get a security exception when I run it froma network shared drive?

Default security policy gives only a restricted set ofpermissions to code that comes from the local intranet zone. This zone isdefined by the Internet Explorer security settings, and should be configured tomatch the local network within an enterprise. Since files named by UNC or by amapped drive (such as with the NET USE command) are being sent over this localnetwork, they too are in the local intranet zone.


The default is set for the worst case of an unsecured intranet.If your intranet is more secure you can modify security policy (with the .NETFramework Configuration tool or the CASPol tool) to grant more permissions tothe local intranet, or to portions of it (such as specific machine sharenames).




How do I make it so that code runs when the security systemis stopping it?

Security exceptions occur when code attempts to performactions for which it has not been granted permission. Permissions are grantedbased on what is known about code; especially its location. For example, coderun from the Internet is given fewer permissions than that run from the localmachine because experience has proven that it is generally less reliable. So,to allow code to run that is failing due to security exceptions, you must increasethe permissions granted to it. One simple way to do so is to move the code to amore trusted location (such as the local file system). But this won't work inall cases (web applications are a good example, and intranet applications on acorporate network are another). So, instead of changing the code's location,you can also change security policy to grant more permissions to that location.This is done using either the .NET Framework Configuration tool or the codeaccess security policy utility (caspol.exe). If you are the code's developer orpublisher, you may also digitally sign it and then modify security policy togrant more permissions to code bearing that signature. When taking any of theseactions, however, remember that code is given fewer permissions because it isnot from an identifiably trustworthy source—before you move code to your localmachine or change security policy, you should be sure that you trust the codeto not perform malicious or damaging actions.




How do I administersecurity for my machine? For an enterprise?

The .NET Framework includes the .NET Framework Configurationtool, an MMC snap-in (mscorcfg.msc), to configure several aspects of the CLRincluding security policy. The snap-in not only supports administering securitypolicy on the local machine, but also creates enterprise policy deploymentpackages compatible with System Management Server and Group Policy. A commandline utility, CASPol.exe, can also be used to script policy changes on thecomputer. In order to run either tool, in a command prompt, change the currentdirectory to the installation directory of the .NET Framework (located in%windir%\Microsoft.Net\Framework\v1.0.2914.16\) and type mscorcfg.msc orcaspol.exe.




How does evidence-based security work with Windows 2000 security?

Evidence-based security (which authorizes code) workstogether with Windows 2000 security (which is based on log on identity). Forexample, to access a file, managed code must have both the code access securityfile permission and must also be running under a log on identity that has NTFSfile access rights. The managed libraries that are included with the .NETFramework also provide classes for role-based security. These allow theapplication to work with Windows log on identities and user groups.


Brijesh Pandya 



job opportunitya said...

I look for blogs as great as your work. Fine
blog. I found your site suitable for another visit!
Jump into my plastic surgery philadelphia blog.

job opportunitya said...

Fascinating blog. I loved the site you did a good
job on it, I will be back! I surf the net for blog
like this one.
Look who checking out my charlotte plastic surgery blog?