Thursday, May 1, 2008

What’s New with .NET 2.0

Agenda
Improvements to the Platform
Improvements to the Languages
Improvements to the Framework (BCL)
Improvements to the Tools



Common Language Runtime 2.0
Generics
Create generic classes whose type is specified by the class consumer
Vastly improved performance
Code errors are detected at compile-time
Edit & Continue
Best feature of Visual Basic 6.0!
Halt application execution in the debugger, change a line of code and continue execution without recompiling
Performance & Load time
CLR loads faster and with a smaller memory footprint



Platform Improvements
64-Bit Platform Support
Build managed 64-bit applications
InterOp with 64-bit native applications
Improved ASP .NET administration and caching
ASP .NET Web Site Administration Tool
IIS 6.0 Kernel-level Caching
Improved Smart (Rich) Client Deployment
ClickOnce
Improved COM InterOp performance
Ability to wrap native function pointers into delegates
Faster call performance between applications in different application domains
Improved XML Serialization performance
Improves Web Service performance



.NET Language Improvements / Enhancements
Generics
Partial Classes
Classes can be split across multiple files
Incredibly useful for classes whose implementation is specified partially by a tool
E.g. ASP .NET, WinForms, Web Service proxies
Iterators
New syntax to support easy implementation of custom class iterators
Anonymous Methods
… and much more!
(come see me in tomorrow’s session!)



Generics Example
public class MyList<> {
private Node head;
private class Node {
private Node next;
private Type data;
public Node( Type t ) {
next = null;
data = t;
}
public void Add( Type t ) {
Node n = new Node( t );
n.Next = head;
head = n;
}
MyList list;
list = new MyList();
for(int i = 0; i<10;i++)
{
list.Add(i);
}

Partial Classes Example
public partial class MySplitClass {
private int _foo = 0;
public MySplitClass( int foo ){
_foo = foo;
_bar = foo + 5;
}
}
public partial class MySplitClass {
private int _bar = 0;
public int Bar { get { return _bar; } }
public int Foo { get { return _foo; } }
}



What’s new in the BCL?
Compression Support (Gzip)
System.IO.Compression
ACLs Support
Manipulate and manage ACLs from managed code
System.Security
SecureString
Used for holding confidential data
Base Collections
Overhauled to support collections
New LinkedList and Stack collections!
System.Collections
Improved Encryption Support
System.Security.Encryption



System.IO.Compression.GZipStream Example
using System.IO.Compression;
using System.IO;
public class Unzip
{
public int UnzipFile(string filename)
{
FileStream fs;
try
{
fs = new FileStream( filename, FileMode.Open, FileAccess.Read, FileShare.Read );
byte[] buffer = new byte[fs.Length -1];
if( buffer.Length != fs.Read( buffer, 0, buffer.Length ) )
{
fs.Close();
throw new IOException( "Failed to read data from file" );
}
fs.Close();
MemoryStream ms = new MemoryStream();
GZipStream zipStream = new GZipStream( ms, CompressionMode.Decompress );
byte[] decompressBuffer = new byte[buffer.Length + 100];
int offset = 0;
while( true ) {
if( 0 == zipStream.Read( decompressBuffer, offset, 100 ) )
break;
else
offset += 100;
}
zipStream.Close();
// decompressBuffer now contains the original bytes
}
}



What’s new in the BCL? (…cont’d)
New network classes
Support for FTP
Ability to respond to network interface changes (disconnected cable, wireless LAN out of range)
HTTPWebListener
Supported by Windows 2003 and Windows XP SP2
Requires new HTTP.SYS
Supports hosting the ASP .NET runtime without IIS!
Now client applications can host web services!
SerialPort component
Semaphore class for Threading
System.Transactions namespace
Leverage DTC without the rest of System.EnterpriseServices



What’s new in ASP .NET 2.0?
Master Pages
Themes & Skins
Web Site Administration Tool
New Security Controls
Profile Management
Site Navigation Controls & Management
Web Parts
More than 45 new web controls!
Security, data access, navigation, image generation, menus, tree views, portals, and more!
All built-in controls are now mobile enabled!




What’s new in Smart Clients (WinForms) 2.0?
Big Changes!
67% more public types
127% more public properties
XP Themes Support
Application.EnableVisualStyles();
Control Layout improvements
Snap-To Alignment 
Layout Controls



WinForms 2.0 Layout Controls

Easier layout and resizing management of complex forms
Flow Layout: similar to ASP .NET (HTML) flow layout


Table Layout: form organized via rows and columns (one control per cell)



WinForms 2.0: Property Editing Mode
Enables in-place editing of properties



WinForms 2.0: New Controls
GridView
New version of GridControl
More intuitive object model for manipulating bound data
Supports Smart Tags for rapidly binding to a data source
MenuStrip
Powerful new menu tool with incredible rendering capabilities
WebBrowser
Managed IE .NET Component
SoundPlayer
Simples component to add sound to your applications
BackgroundWorker
Simplifies the task of using worker threads to retrieve data required by the UI



ClickOnce Deployment
Vastly simplified Smart Client development!
Rich Client applications with deployment and updates as simple as a web application
Invoked via BuildPublish Solution menu item



ClickOnce Configuration
Select Project  Properties
Brand new UI for manipulating project properties
Deployment Options:
Web Server
File Share
Update Options:
Check for updates when application starts
Check for updates in background while application is running
Allow whether or not user can accept update
Prerequisite Options:
dotnetfx
Windows installer
MDAC
SQL Server 2005 Express Edition
J# redistributable package



Project Properties




What’s new in ADO .NET 2.0?
Bulk Copy Operation
Enables bulk copying of one data source to another
Fastest way to transfer data from one source to another
Batch Update
Big performance improvement
Enables multiple rows to be updated in a single round trip
Used by the DataAdapter.Update() method
Batch size is set using UpdateBatchSize property
Data Paging
New method of the command object:
ExecutePageReader( Behavior, startIndex, pageSize)
Vastly simplified pagination logic



What else is new in ADO .NET 2.0?
Connection Statistics
Enables tracking of database statistics (data transferred, transactions, user details, …)
Set via Connection.StatisticsEnabled property
Statistics retrieved via Connection.RetrieveStatistics()
Statistics reset via Connection.ResetStatistics()
DataSet.RemotingFormat
Significant performance improvement for remoting a DataSet
Setting
ds.RemotingFormat = SerializationFormat.Binary;
results in binary wire serialization
New & Improved DataTable class
Supports Load() and Save() methods to directly load XML
No more DataSet objects with a single DataTable!



More ADO .NET Goodies!
New & Improved DataReader functionality
ExecutePageReader()
ExecuteResultSet()
ExecuteRow()



ADO .NET Common Provider Model
Simplified development of provider independent applications
DbProviderFactory class provides two methods:
GetFactoryClasses: Retrieves all providers installed on the machine
GetFactory( string ProviderName): Retrieves the provider class associated with the given name



What’s new in Web Services?
namespace WebService
{
[WebServiceBinding(
ConformanceClaims=WsiClaims.BP10 ]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
ConformanceClaims attribute alters the Web Services stack behavior to work in accordance with WS-I Basic Profile 1.0
Exceptions are thrown for logic that breaks compliance



XML Serialization Improvements
Performance hit when Web Service proxy is first instantiated
Direct result of code generation / class compilation for serialization logic
.NET 2.0 introduces a new tool: SGEN.exe
Generates the serialization class at design-time
Place the resulting binary in the same path as your client and the pre-compiled class will be used at runtime



WSDL.exe Improvements
Problem occurred in ASMX v1.x when two web services exposed the same custom type (i.e. “Customers” class)
Proxies generated by WSDL.exe would generate two separate instances of “Customer” which were not interchangeable.
Problem solved with new “/shareTypes” flag:
wsdl.exe /out:proxies.cs /shareTypes
http://localhost/CustomerService/CustomerMgmt.asmx?wsdl
http://localhost/CustomerService/CustomerInfo.asmx?wsdl
Creates one source file “proxies.cs” which contains proxy implementations for both web services as well as a single .NET representation of the “Customer” object

Some Impoartant questions Of Asp.Net

1. What are the main differences between asp and asp.net?
ASP 3.0

• Supports VBScript and JavaScript
o scripting languages are limited in scope
o interpreted from top to bottom each time the page is loaded
• Files end with *.asp extension
• 5 objects: Request, Response, Server, Application, Session
• Queried databases return recordsets
• Uses conventional HTML forms for data collection

ASP .NET

• Supports a number of languages including Visual Basic, C#, and JScript
o code is compiled into .NET classes and stored to speed up multiple hits on a page
o object oriented and event driven makes coding web pages more like traditional applications
• Files end with *.aspx extension
• .NET contains over 3400 classes
• XML-friendly data sets are used instead of recordsets
• Uses web forms that look like HTML forms to the client, but add much functionality due to server-side coding
• Has built-in validation objects
• Improved debugging feature (great news for programmers)
• ASP .NET controls can be binded to a data source, including XML recordsets

2. What is a user control?

• An ASP.NET user control is a group of one or more server controls or static HTML elements that encapsulate a piece of functionality. A user control could simply be an extension of the functionality of an existing server control(s) (such as an image control that can be rotated or a calendar control that stores the date in a text box). Or, it could consist of several elements that work and interact together to get a job done (such as several controls grouped together that gather information about a user's previous work experience).
Source: 15seconds.com

3. What are different types of controls available in ASP.net?
• HTML server controls HTML elements exposed to the server so you can program them. HTML server controls expose an object model that maps very closely to the HTML elements that they render.
• Web server controls Controls with more built-in features than HTML server controls. Web server controls include not only form-type controls such as buttons and text boxes, but also special-purpose controls such as a calendar. Web server controls are more abstract than HTML server controls in that their object model does not necessarily reflect HTML syntax.
• Validation controls Controls that incorporate logic to allow you to test a user's input. You attach a validation control to an input control to test what the user enters for that input control. Validation controls are provided to allow you to check for a required field, to test against a specific value or pattern of characters, to verify that a value lies within a range, and so on.
• User controls Controls that you create as Web Forms pages. You can embed Web Forms user controls in other Web Forms pages, which is an easy way to create menus, toolbars, and other reusable elements.
• Note You can also create output for mobile devices. To do so, you use the same ASP.NET page framework, but you create Mobile Web Forms instead of Web Forms pages and use controls specifically designed for mobile devices.
Source: MSDN

4. What are the validation controls available in ASP.net?
Type of validation Control to use
Description

Required entry RequiredFieldValidator Ensures that the user does not skip an entry.
Comparison to a value CompareValidator Compares a user's entry against a constant value, or against a property value of another control, using a comparison operator (less than, equal, greater than, and so on).
Range checking RangeValidator Checks that a user's entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates.
Pattern matching RegularExpressionValidator Checks that the entry matches a pattern defined by a regular expression. This type of validation allows you to check for predictable sequences of characters, such as those in social security numbers, e-mail addresses, telephone numbers, postal codes, and so on.
User-defined CustomValidator Checks the user's entry using validation logic that you write yourself. This type of validation allows you to check for values derived at run time.
Source: MSDN

5. How will you upload a file to IIS in Asp and how will you do the same in ASP.net?

First of all, we need a HTML server control to allow the user to select the file. This is nothing but the same old tag, with the type set to File, such as . This will give you the textbox and a browse button. Once you have this, the user can select any file from their computer (or even from a network). Then, in the Server side, we need the following line to save the file to the Web Server.


myFile.PostedFile.SaveAs ("DestinationPath")

Note: The Form should have the following ENC Type


Source: ASP Alliance
6. What is Attribute Programming? What are attributes? Where are they used?
Attributes are a mechanism for adding metadata, such as compiler instructions and other data about your data, methods, and classes, to the program itself. Attributes are inserted into the metadata and are visible through ILDasm and other metadata-reading tools. Attributes can be used to identify or use the data at runtime execution using .NET Reflection.
Source: OnDotNet.com

7. What is the difference between Data Reader & Dataset?
Data Reader is connected, read only forward only record set.
Dataset is in memory database that can store multiple tables, relations and constraints; moreover dataset is disconnected and is not aware of the data source.

8. What is the difference between server side and client side code?
Server code is executed on the web server where as the client code is executed on the browser machine.

9. Why would you use “EnableViewState” property? What are the disadvantages?
EnableViewState allows me to retain the values of the controls properties across the requests in the same session. It hampers the performance of the application.

10. What is the difference between Server. Transfer and Response. Redirect?

The Transfer method allows you to transfer from inside one ASP page to another ASP page. All of the state information that has been created for the first (calling) ASP page will be transferred to the second (called) ASP page. This transferred information includes all objects and variables that have been given a value in an Application or Session scope, and all items in the Request collections. For example, the second ASP page will have the same SessionID as the first ASP page.

When the second (called) ASP page completes its tasks, you do not return to the first (calling) ASP page. All these happen on the server side browser is not aware of this.
The redirect message issue HTTP 304 to the browser and causes browser to got the specified page. Hence there is round trip between client and server. Unlike transfer, redirect doesn’t pass context information to the called page.

11. What is the difference between Application_start and Session_start?
Application_start gets fired when an application receive the very first request.
Session_start gets fired for each of the user session.



12. What is inheritance and when would you use inheritance?

The concept of child class inheriting the behavior of the parent is called inheritance.
If there are many classes in an application that have some part of their behavior common among all , inheritance would be used.

13. What is the order of events in a web form?

1. Init
2. Load
3. Cached post back events
4. Prerender
5. Unload

14. Can you edit Data in repeater control?

No

15. Which template you must provide to display data in a repeater control?

Item Template

16. How can you provide an alternating color scheme in a Data Grid?

Use ALTERNATINGITEMSTYLE and ITEMSTYLE, attributes or Templates

17. Is it possible to bind a data to Textbox?
Yes

18. What method I should call to bind data to control?
Bind Data ()

19. How can I kill a user session?
Call session. abandon.

21. Which is the common property among all the validation controls?
ControlToValidate

22. How do you bind a data grid column manually?

Use BoundColumn tag.

23. Web services can only be written in .NET, true or false?
False

24. What does WSDL, UDDI stands for?
Web Service Description Language.
Universal Description Discovery and Integration
25. How can you make a property read only? (C#)
Use key word Read Only

25. Which validation control is used to match values in two controls?
Compare Validation control.

26. To test a Web Service I must create either web application or windows application. True or false?

False

27. How many classes can a single .NET assembly contains?
Any number

28. What are the data types available in JavaScript?

Object is the only data type available.

29. Is it possible to share session information among ASP and ASPX page?

No, it is not possible as both of these are running under different processes.

30. What are the caching techniques available?
Page cahahing.
Fragment Caching
And Data Caching



31. What are the different types of authentication modes available?

1. Window.
2. Form.
3. Passport.
4. None.

32. Explain the steps involved to populate dataset with data?
Open connection
Initialize Adapter passing SQL and connection as parameter
Initialize Dataset
Call Fill method of the adapter passes dataset as the parameter
Close connection.

33. Can I have data from two different sources into a single dataset?
Yes, it is possible.

34. Is it possible load XML into a Data Reader?
No.

35. Is it possible to have tables in the dataset that are not bound to any data source?

Yes, we can create table object in code and add it to the dataset.

36. Why do you deploy an assembly into GAC?
To allow other application to access the shared assembly.

37. How do you uninstall assembly from GAC?

Use Gacutil.exe with U switch.

38. What does Regasm do?

The Assembly Registration tool reads the metadata within an assembly and adds the necessary entries to the registry, which allows COM clients to create .NET Framework classes transparently. Once a class is registered, any COM client can use it as though the class were a COM class. The class is registered only once, when the assembly is installed. Instances of classes within the assembly cannot be created from COM until they are actually registered.

39. What is the difference between Execute Scalar and ExceuteNoneQuery?
Execute Scalar returns the value in the first row first column of a query result set.
ExceuteNonQuery return number of rows affected.

40. What is an assembly?

Assembly is a deployment unit of .NET application. In practical terms assembly is an Executable or a class library.

41. What is CLR?
The common language runtime is the execution engine for .NET Framework 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, and pre-existing DLLs (unmanaged code and data)
• Automation of object layout
• Support for developer services (profiling, debugging, and so on)

42. What is the common type system (CTS)?
The common type system is a rich type system, built into the common language runtime that supports the types and operations found in most programming languages. The common type system supports the complete implementation of a wide range of programming languages.

43. What is the Common Language Specification (CLS)?

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

44. What is the Microsoft Intermediate Language (MSIL)?

MSIL is the CPU-independent instruction set into which .NET Framework programs are compiled. It contains instructions for loading, storing, initializing, and calling methods on objects.
Combined with metadata and the common type system, MSIL allows for true cross-language integration.
Prior to execution, MSIL is converted to machine code. It is not interpreted.

45. What is managed code and managed data?

Managed code is code that is written to target the services of the common language runtime (see what is the Common Language Runtime?). In order to target these services, the code must provide a minimum level of information (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 by default, but the compiler can produce managed code by specifying a command-line switch (/CLR).
Closely related to managed code is managed data—data that is allocated 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. Visual Studio .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 by using the __gc keyword. As the name suggests, this means that the memory for instances of the class is managed by the garbage collector. In addition, the class becomes a full participating member of the .NET Framework community, with the benefits and restrictions that brings. An example of a benefit is proper interoperability with classes written in other languages (for example, a managed C++ class can inherit from a Visual Basic class). An example of a restriction is that a managed class can only inherit from one base class.

46. What is an assembly?

An assembly is the primary building block of a .NET Framework 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 within their 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 text name), version, culture, and digital signature (if the assembly is to be shared across applications).
Defines what files (by name and file hash) make up the assembly 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 assembly to run properly.

This information is used at run time to resolve references, enforce version binding policy, and validate the integrity of loaded assemblies. The runtime can determine and locate the assembly for any running object, since every type is loaded in the context of an assembly. Assemblies are also the unit at which code access security permissions are applied. The identity evidence for each assembly is considered separately when determining what permissions to grant the code it contains.
The self-describing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible.

47. What are private assemblies and shared assemblies?
A private assembly is used only by a single application, and is 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 this purpose by giving it a cryptographically strong name (referred to as a strong name). By contrast, a private assembly name need only be unique within the application that uses it.
By making a distinction between private and shared assemblies, we introduce the notion of sharing as an explicit decision. Simply by deploying private assemblies to an application directory, you can guarantee that that application will run only with the bits it was built and deployed with. References to private assemblies will only be resolved locally to the private application directory.
There are several reasons you may elect to build and use shared assemblies, such as the ability to express version policy. The fact that shared assemblies have a cryptographically strong name means that only the author 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 version of an assembly, you can have some confidence that version updates will be controlled and verified by the author. Otherwise, you don't have to accept them.
For locally installed applications, a shared assembly is typically explicitly installed into the global assembly cache (a local cache of assemblies maintained by the .NET Framework). Key to the version management features of the .NET Framework is that downloaded code does not affect the execution of locally installed applications. Downloaded code is put in a special download cache and is not globally available on the machine even if some of the downloaded components are built as shared assemblies.
The classes that ship with the .NET Framework are all built as shared assemblies.

48. If I want to build a shared assembly, does that require the overhead of signing and managing key pairs?

Building a shared assembly does involve working with cryptographic keys. Only the public key is strictly needed when the assembly is being built. Compilers targeting the .NET Framework provide command line options (or use custom attributes) for supplying the public key when building the assembly. It is common to keep a copy of a common public key in a source database and point build scripts to this key. Before the assembly is shipped, the assembly must be fully signed with the corresponding private key. This is done using an SDK tool called SN.exe (Strong Name).
Strong name signing does not involve certificates like Authenticode does. There are no third party organizations involved, no fees to pay, and no certificate chains. In addition, the overhead for verifying a strong name is much less than it is for Authenticode. However, strong names do not make any statements about trusting a particular publisher. Strong names allow you to ensure that the contents of a given assembly haven't been tampered with, and that the assembly loaded on your behalf at run time comes from the same publisher as the one you developed against. But it makes no statement about whether you can trust the identity of that publisher.

49. What is the difference between a namespace and an assembly name?

A namespace is a logical naming scheme for types in which a simple type name, such as MyType, is preceded with a dot-separated hierarchical name. Such a naming scheme is completely under the control of the developer. For example, types MyCompany.FileAccess.A and MyCompany.FileAccess.B might be logically expected to have functionality related to file access. The .NET Framework uses a hierarchical naming scheme for grouping types into logical categories of related functionality, such as the Microsoft® ASP.NET application framework, or remoting functionality. Design tools can make use of namespaces to 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 single assembly may contain types whose hierarchical names have different namespace roots, and a logical namespace root may span multiple assemblies. In the .NET Framework, a namespace is a logical design-time naming convenience, whereas an assembly establishes the name scope for types at run time.

50. What options are available to deploy my .NET applications?

The .NET Framework simplifies deployment by making zero-impact install and XCOPY deployment of applications feasible. Because all requests are resolved first to the private application directory, simply copying an application's directory files to disk is all that is needed to run the application. No registration is required.
This scenario is particularly compelling for Web applications, 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 the availability of shared assemblies, or when the application is not locally installed (but rather downloaded on demand). For these cases, the .NET Framework provides extensive code download services and integration with the Windows Installer. The code download support provided by the .NET Framework offers several advantages over current platforms, including incremental download, code access security (no more Authenticode dialogs), and application isolation (code downloaded on behalf of one application doesn't affect other applications). The Windows Installer is another powerful deployment mechanism available to .NET applications. All of the features of Windows Installer, including publishing, advertisement, and application repair will be available to .NET applications in Windows Installer 2.0.

51. If you have an assembly and that you want to use in more than one application. Where do I deploy it?

Assemblies that are to be used by multiple applications (for example, shared assemblies) are deployed to the global assembly cache. In the prerelease and Beta builds, use the /i option to the GACUtil SDK tool to install an assembly into the cache:
gacutil /i myDll.dll
Windows Installer 2.0, which ships with Windows XP and Visual Studio .NET will be able to install assemblies into the global assembly cache.

52. How can I see what assemblies are installed in the global assembly cache?
The .NET Framework ships with a Windows shell extension for viewing the assembly cache. Navigating to % windir%\assembly with the Windows Explorer activates the viewer.

53. What is an application domain?

An application domain (often AppDomain) is a virtual process that serves to isolate an application. All objects created within the same application scope (in other words, anywhere along the sequence of object activations beginning with the application entry point) are created within the same application domain. Multiple application domains can exist in a single operating system process, making them a lightweight means of application isolation.

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

54. What is garbage collection?
Garbage collection is a mechanism that allows the computer to detect when an object can no longer be accessed. It then automatically releases the memory used by that object (as well as calling a clean-up routine, called a "finalizer," which is written by the user). Some garbage collectors, like the one used by .NET, compact memory and therefore decrease your program's working set.

55. How does non-deterministic garbage collection affect my code?

For most programmers, having a garbage collector (and using garbage collected objects) means that you never have to worry about deallocating memory, or reference counting objects, even if you use sophisticated data structures. It does require some changes in coding style, however, if you typically deallocate system resources (file handles, locks, and so 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 the system resources deterministically (that is, under your program control) and let the garbage collector release the memory when it compacts the working set.

56. Can I avoid using the garbage collected heap?

All languages that target the runtime allow you to allocate class objects from the garbage-collected heap. This brings benefits in terms of fast allocation, and avoids the need for programmers to work out when they should explicitly 'free' each object.
The CLR also provides what are called ValueTypes—these are like classes, except that ValueType objects are allocated on the runtime stack (rather than the heap), and therefore reclaimed automatically when your code exits the procedure in which they are defined. This is how "structs" in C# operate.
Managed Extensions to C++ lets you choose where class objects are allocated. If declared as managed Classes, with the __gc keyword, then they are allocated from the garbage-collected heap. If they don't include the __gc keyword, they behave like regular C++ objects, allocated from the C++ heap, and freed explicitly with the "free" method.

57. How do in-process and cross-process communication work in the Common Language Runtime?
There are two aspects to in-process communication: between contexts within a single application domain, or across application domains. Between contexts in the same application domain, proxies are used as an interception mechanism. No marshaling/serialization is involved. When crossing application domains, we do marshaling/serialization using the runtime binary protocol.
Cross-process communication uses a pluggable channel and formatter protocol, each suited to a specific purpose.
If the developer specifies an endpoint using the tool soapsuds.exe to generate a metadata proxy, HTTP channel with SOAP formatter is the default.
If a developer is doing explicit remoting in the managed world, it is necessary to be explicit about what channel and formatter to use. This may be expressed administratively, through configuration files, or with API calls to load specific channels. Options are:
HTTP channel w/ SOAP formatter (HTTP works well on the Internet, or anytime traffic must travel through firewalls)
TCP channel w/ binary formatter (TCP is a higher performance option for local-area networks (LANs))
When making transitions between managed and unmanaged code, the COM infrastructure (specifically, DCOM) is used for remoting. In interim releases of the CLR, this applies also to serviced components (components that use COM+ services). Upon final release, it should be possible to configure any remotable component.
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 remoting infrastructure of the CLR. 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.

58. Can I use COM objects from a .NET Framework program?

Yes. Any COM component you have deployed today can be used from managed code, and in common cases the adaptation is totally automatic.
Specifically, COM components are accessed from the .NET Framework by use of a runtime callable wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET Framework-compatible interfaces. For OLE automation interfaces, the RCW can be generated automatically from a type library. For non-OLE automation interfaces, a developer may write a custom RCW and manually map the types exposed by the COM interface to .NET Framework-compatible types.



59. Can .NET Framework components be used from a COM program?

Yes. Managed types you build today can be made accessible from COM, and in the common case the configuration is totally automatic. There are certain new features of the managed development environment that are not accessible from COM. For example, static methods and parameterized constructors cannot be used from COM. In general, it is a good idea to decide in advance who the 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, it may or may not be visible by default.
Specifically, .NET Framework components are accessed from COM by using a COM callable wrapper (CCW). This is similar to an RCW (see previous question), but works in the opposite direction. Again, if the .NET Framework development tools cannot automatically generate the wrapper, or if the automatic behavior is not what you want, a custom CCW can be developed.

60. Can I use the Win32 API from a .NET Framework program?

Yes. Using platform invoke, .NET Framework programs can access native code libraries by means of static DLL entry points.
Here is an example of C# calling the Win32 MessageBox function:
using System;
using System.Runtime.InteropServices;

class MainApp
{
[DllImport("user32.dll", EntryPoint="MessageBox")]
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 );
}
}

61. What do I have to do to make my code work with the security system?

Usually, not a thing—most applications will run safely and will not be exploitable by malicious attacks. By simply using the standard class libraries to access resources (like files) or perform protected operations (such as a reflection on private members of a type), security will be enforced by these libraries. The one simple thing application developers may want to do is include a permission request (a form of declarative security) to limit the permissions their code may receive (to only those it requires). This also ensures that if the code is allowed to run, it will do so with all the permissions it needs.
Only developers writing new base class libraries that expose new kinds of resources need to work directly with the security system. Instead of all code being a potential security risk, code access security constrains this to a very small bit of code that explicitly overrides the security system.

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

Default security policy gives only a restricted set of permissions to code that comes from the local intranet zone. This zone is defined by the Internet Explorer security settings, and should be configured to match the local network within an enterprise. Since files named by UNC or by a mapped drive (such as with the NET USE command) are being sent over this local network, 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 .NET Framework Configuration tool or the CASPol tool) to grant more permissions to the local intranet, or to portions of it (such as specific machine share names).

63. How do I make it so that code runs when the security system is stopping it?
Security exceptions occur when code attempts to perform actions for which it has not been granted permission. Permissions are granted based on what is known about code; especially its location. For example, code run from the Internet is given fewer permissions than that run from the local machine 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 increase the permissions granted to it. One simple way to do so is to move the code to a more trusted location (such as the local file system). But this won't work in all cases (web applications are a good example, and intranet applications on a corporate 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 code access security policy utility (caspol.exe). If you are the code's developer or publisher, you may also digitally sign it and then modify security policy to grant more permissions to code bearing that signature. When taking any of these actions, however, remember that code is given fewer permissions because it is not from an identifiably trustworthy source—before you move code to your local machine or change security policy, you should be sure that you trust the code to not perform malicious or damaging actions.

64. How do I administer security for my machine? For an enterprise?
The .NET Framework includes the .NET Framework Configuration tool, an MMC snap-in (mscorcfg.msc), to configure several aspects of the CLR including security policy. The snap-in not only supports administering security policy on the local machine, but also creates enterprise policy deployment packages compatible with System Management Server and Group Policy. A command line utility, CASPol.exe, can also be used to script policy changes on the computer. In order to run either tool, in a command prompt, change the current directory to the installation directory of the .NET Framework (located in %windir%\Microsoft.Net\Framework\v1.0.2914.16\) and type mscorcfg.msc or caspol.exe