.NET FAQ 'S
How does ASP page work?
An ASP page is an HTML page that contains server-side scripts written on VBScript or Jscript or Perl that are processed by the Web server before being sent to the user’s browser. ASP can be combined with HTML, XML and COM to create Web sites. Server-side scripts run when a browser requests an .asp file from the Web server. ASP is called by the Web server, which processes the requested file and executes script commands. It then formats a standard Web page and sends it to the browser.
Web Forms pages are built with ASP.NET technology. ASP.NET is built on the .NET Framework, so the entire framework is available to any ASP.NET application. Your applications can be written in any language compatible with the common language runtime, including Microsoft Visual Basic, Visual C#, and JScript .NET.The ASP.NET page framework is a programming framework that runs on a Web server to dynamically produce and manage Web Forms pages. Web Forms pages run on any browser or client device.
How do you create a permanent cookie?
Dim oCookie As New
HttpCookie(“permanentCookie”,”squared”)
oCookie.Expires=#24/11/2006#
Response.Cookies.Add(oCookie)
What is ViewState? What does the “EnableViewState” property do? Whay would I want it on or off?
View state is a property of Web Forms page and each control of the page to save their values so it can be used between round trips to the server.When the page is processed, the current state of the page and controls is inserted into a string and saved in the page as a hidden field. When the page is posted back to the server, the page parses the view state string at page initialization and restores property information in the page.
EnableViewState indicates whether the page maintains its view state, and the view state of any server controls it contains, when the current page request ends.
The benefits of using ViewState are it automatically store values between multiple requests for the same page, it is saved as a hidden field of the page and no server resources required.
It is better to disable ViewState if a control or a page contain large amount of data. Saving such an amount can affect the form load. Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it.
Give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?
In Application_Start you can initialize the variables, upload data from database table and store in ViewState or in Cache.
In Session_Start you can count the number of active sessions, automatically redirect users to the certain Web page at the beginning of the session.
Describe the role of global.asax?
The Global.asax file is an optional file that contains code for responding to application-level events raised by ASP.NET or by HttpModules and initializing global application objects. The Global.asax file resides in the root directory of an ASP.NET-based application.
How can you debug your.NET application?
You can debug .NET application
using Visual Studio .NET.
If Visual Studio .NET is not installed you can use Systems.Diagnostics classes,
Runtime Debugger (Cordbg.exe), or Microsoft Common Language Runtime Debugger (DbgCLR.exe)
System.Diagnostics includes the Trace and Debug classes for tracing execution flow, and the Process, EventLog, and PerformanceCounter classes for profiling code.The Cordbg.exe command-line debugger can be used to debug managed code from the command-line interpreter.
DbgCLR.exe is a debugger with the Windows interface for debugging managed code.
How do you deploy your ASP.NET application?
To create ASP.NET Web applications, you use a standard deployment model: your project is compiled and the resulting files are deployed. The Web Forms code-behind class file (.aspx.vb, or .aspx.cs) is compiled into a project .dll file along with all other class files included in your project. This single project .dll file is then deployed to the server, without any source code. When a request for the page is received, the project .dll file is instantiated and executed.
Where do we store our connection string in ASP.NET application?
You can store Connection String in Web.config file:
create a new add key in the appSettings element.
Or in the Registry
add new subkeys to the SOFTWARE key in the HKEY_LOCAL_MACHINE
Explain security types in ASP.NET?
ASP.NET, in conjunction with
Microsoft Internet Information Services (IIS), can authenticate user credentials
such as names and passwords using any of the following authentication methods:
• Windows: Basic, digest, or Integrated Windows Authentication. If the user
making the request has already been authenticated in a Windows-based network,
IIS can pass the user’s credentials through when requesting access to a
resource.
• Microsoft Passport
authentication
Passport authentication allows implementing single sign-in for multiple
applications or websites that want to authenticate users. The user is expected
to use only one username and password to access all the sites.
• Forms authentication
generally refers to a system in which unauthenticated requests are redirected to
a registration form. The user provides credentials and submits the form. If the
application authenticates the request, the system issues a cookie that contains
the credentials or a key for reacquiring the identity.
• Client Certificate authentication
IIS supports the use of digital
certificates and the secure sockets layer (SSL). In this scenario, either the
server or the client has a certificate — a digital identification — that they
have obtained from a third-party source. The certification is passed to
your application with requests. It can be mapped to a Windows user account and
granted appropriate permissions.
Explain different Authentication modes in ASP.NET?
Authentication modes are: Windows, Forms, Passport, or None.
ASP.NET uses Windows
authentication in conjunction with IIS authentication. It authenticates the
identity using basic, digest, or Integrated Windows authentication, or some
combination of them.
All users are authenticated as soon as they log on to Windows.
Passport authentication is centralized authentication service provided by Microsoft that offers a single log on and core profile services for member sites.
Form authentication generally refers to a system in which unauthenticated requests are redirected to a registration form. The user provides credentials and submits the form. If the application authenticates the request, the system issues a cookie that contains the credentials or a key for reacquiring the identity.
None authentication is used when you want to apply anonymous authentication or a custom authentication scheme.
How to do forms authentication in ASP.NET?
You need to create an entry in
Web.Config
authentication mode=”Forms”
forms
name=”.TheCookie”
loginUrl=”/login/login.aspx”
protection=”All”
timeout=”70″
path=”/”/
/authentication
How can you debug an ASP page, without touching the code?
You can debug ASP page using either the Microsoft Script Debugger or Visual InterDev
How can you handle Exceptions in ASP.NET?
You can handle Exceptions using Try Catch Finally block.
Also in Global.asax you can create an application-wide error handler Application_Error or create a handler in a page for the Page_Error event. Application_Error and Page_Error methods are called if an unhandled exception occurs anywhere in your page or application.
You can also use the Page class
property ErrorPage that gets or sets the error page to which the requesting
browser is redirected in the event of an unhandled page exception.
It works only when customErrors mode is on in Web.Config or Machine.Config.
The sub-element error of customErrors element in Web.Config can be used to define one custom error redirect associated with an HTTP status code and
defaultRedirect attribute is used to specify the default URL to direct a browser to if an error occurs. When defaultRedirect is not specified, a generic error is displayed instead.
Which is the namespace used to write error message in event Log File?
Namespace: System.Diagnostics
What is the namespace for encryption?
System.Security.Cryptography
What is the difference between application and cache variables?
ASP.NET allows you to save values
using application state (an instance of the HttpApplicationState class) for each
active Web application. Application state is a global storage mechanism
accessible from all pages in the Web application and is thus useful for storing
information that needs to be maintained between server round trips and between
pages.
The memory occupied by variables stored in application state is not released
until the value is either removed or replaced.
Application state is a key-value dictionary structure created during each
request to a specific URL. You can add your application-specific information to
this structure to store it between page requests.
Once you add your application-specific information to application state, the
server manages it.
Cache data can persist for a long time, but not across application restarts. It can hold both large and small amounts of data effectively. Also, data can expire based on time set by the application code or other dependencies; this feature is not available in the Application object.
What is the difference between control and component?
Components implement the System.ComponentModel.IComponent interface by deriving from the SystemComponent.Model.Component base class. Component is generally used for an object that is reusable and can interact with other objects. A .NET Framework component additionally provides features such as control over external resources and design-time support.
A control is a component that
provides user-interface capabilities. Controls draw themselves and shown in the
visual area.
The .NET Framework provides two base classes for controls: one for client-side
Windows Forms controls and the other for ASP.NET server controls. These are
System.Windows.Forms.Control and System.Web.UI.Control.
System.Windows.Forms.Control derives from Component base class and itself
provides UI capabilities.
System.Web.UI.Control implements IComponent and provides the infrastructure on
which it is easy to add UI functionality.
1.
Introduction
1.1 What is .NET?
.NET is a general-purpose software development platform, similar to Java. At its
core is a virtual machine that turns intermediate language (IL) into machine
code. High-level language compilers for C#, VB.NET and C++ are provided to turn
source code into IL. C# is a new programming language, very similar to Java. An
extensive class library is included, featuring all the functionality one might
expect from a contempory development platform - windows GUI development (Windows
Forms), database access (ADO.NET), web development (ASP.NET), web services, XML
etc.
See also Microsoft's definition.
1.2 When was .NET announced?
Bill Gates delivered a keynote at Forum 2000, held June 22, 2000, outlining the
.NET 'vision'. The July 2000 PDC had a number of sessions on .NET technology,
and delegates were given CDs containing a pre-release version of the .NET
framework/SDK and Visual Studio.NET.
1.3 What versions of .NET are there?
The final versions of the 1.0 SDK and runtime were made publicly available
around 6pm PST on 15-Jan-2002. At the same time, the final version of Visual
Studio.NET was made available to MSDN subscribers.
.NET 1.1 was released in April 2003, and was mostly bug fixes for 1.0.
.NET 2.0 was released to MSDN subscribers in late October 2005, and was
officially launched in early November.
1.4 What operating systems does the .NET Framework run on?
The runtime supports Windows Server 2003, Windows XP, Windows 2000, NT4 SP6a and
Windows ME/98. Windows 95 is not supported. Some parts of the framework do not
work on all platforms - for example, ASP.NET is only supported on XP and Windows
2000/2003. Windows 98/ME cannot be used for development.
IIS is not supported on Windows XP Home Edition, and so cannot be used to host
ASP.NET. However, the ASP.NET Web Matrix web server does run on XP Home.
The .NET Compact Framework is a version of the .NET Framework for mobile
devices, running Windows CE or Windows Mobile.
The Mono project has a version of the .NET Framework that runs on Linux.
1.5 What tools can I use to develop .NET applications?
There are a number of tools, described here in ascending order of cost:
The .NET Framework SDK is free and includes command-line compilers for C++, C#,
and VB.NET and various other utilities to aid development.
SharpDevelop is a free IDE for C# and VB.NET.
Microsoft Visual Studio Express editions are cut-down versions of Visual Studio,
for hobbyist or novice developers.There are different versions for C#, VB, web
development etc. Originally the plan was to charge $49, but MS has decided to
offer them as free downloads instead, at least until November 2006.
Microsoft Visual Studio Standard 2005 is around $300, or $200 for the upgrade.
Microsoft VIsual Studio Professional 2005 is around $800, or $550 for the
upgrade.
At the top end of the price range are the Microsoft Visual Studio Team Edition
for Software Developers 2005 with MSDN Premium and Team Suite editions.
You can see the differences between the various Visual Studio versions here.
1.6 Why did they call it .NET?
I don't know what they were thinking. They certainly weren't thinking of people
using search tools. It's meaningless marketing nonsense.
2.
Terminology
2.1 What is the CLI? Is it the same as the CLR?
The CLI (Common Language Infrastructure) is the definiton of the fundamentals of
the .NET framework - the Common Type System (CTS), metadata, the Virtual
Execution Environment (VES) and its use of intermediate language (IL), and the
support of multiple programming languages via the Common Language Specification
(CLS). The CLI is documented through ECMA - see
http://msdn.microsoft.com/net/ecma/ for
more details.
The CLR (Common Language Runtime) is Microsoft's primary implementation of the
CLI. Microsoft also have a shared source implementation known as ROTOR, for
educational purposes, as well as the .NET Compact Framework for mobile devices.
Non-Microsoft CLI implementations include Mono and DotGNU Portable.NET.
2.2 What is the CTS, and how does it relate to the CLS?
CTS = Common Type System. This is the full range of types that the .NET runtime
understands. Not all .NET languages support all the types in the CTS.
CLS = Common Language Specification. This is a subset of the CTS which all .NET
languages are expected to support. The idea is that any program which uses CLS-compliant
types can interoperate with any .NET program written in any language. This
interop is very fine-grained - for example a VB.NET class can inherit from a C#
class.
2.3 What is IL?
IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language)
or CIL (Common Intermediate Language). All .NET source code (of any language) is
compiled to IL during development. The IL is then converted to machine code at
the point where the software is installed, or (more commonly) at run-time by a
Just-In-Time (JIT) compiler.
2.4 What is C#?
C# is a new language designed by Microsoft to work with the .NET framework. In
their "Introduction to C#" whitepaper, Microsoft describe C# as follows:
"C# is a simple, modern, object oriented, and type-safe programming language
derived from C and C++. C# (pronounced “C sharp”) is firmly planted in the C and
C++ family tree of languages, and will immediately be familiar to C and C++
programmers. C# aims to combine the high productivity of Visual Basic and the
raw power of C++."
Substitute 'Java' for 'C#' in the quote above, and you'll see that the statement
still works pretty well :-).
If you are a C++ programmer, you might like to check out my C# FAQ.
2.5 What does 'managed' mean in the .NET context?
The term 'managed' is the cause of much confusion. It is used in various places
within .NET, meaning slightly different things.
Managed code: The .NET framework provides several core run-time services to the
programs that run within it - for example exception handling and security. For
these services to work, the code must provide a minimum level of information to
the runtime. Such code is called managed code.
Managed data: This is data that is allocated and freed by the .NET runtime's
garbage collector.
Managed classes: This is usually referred to in the context of Managed
Extensions (ME) for C++. When using ME C++, a class can be marked with the __gc
keyword. As the name suggests, this means that the memory for instances of the
class is managed by the garbage collector, but it also means more than that. The
class becomes a fully paid-up member of the .NET community with the benefits and
restrictions that brings. An example of a benefit is proper interop with classes
written in other languages - for example, a managed C++ class can inherit from a
VB class. An example of a restriction is that a managed class can only inherit
from one base class.
2.6 What is reflection?
All .NET compilers produce metadata about the types defined in the modules they
produce. This metadata is packaged along with the module (modules in turn are
packaged together in assemblies), and can be accessed by a mechanism called
reflection. The System.Reflection namespace contains classes that can be used to
interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo
to access type library data in COM, and it is used for similar purposes - e.g.
determining data type sizes for marshaling data across context/process/machine
boundaries.
Reflection can also be used to dynamically invoke methods (see
System.Type.InvokeMember), or even create types dynamically at run-time (see
System.Reflection.Emit.TypeBuilder).
Assemblies
3.1 What is an assembly?
An assembly is sometimes described as a logical .EXE or .DLL, and can be an
application (with a main entry point) or a library. An assembly consists of one
or more files (dlls, exes, html files etc), and represents a group of resources,
type definitions, and implementations of those types. An assembly may also
contain references to other assemblies. These resources, types and references
are described in a block of data called a manifest. The manifest is part of the
assembly, thus making the assembly self-describing.
An important aspect of assemblies is that they are part of the identity of a
type. The identity of a type is the assembly that houses it combined with the
type name. This means, for example, that if assembly A exports a type called T,
and assembly B exports a type called T, the .NET runtime sees these as two
completely different types. Furthermore, don't get confused between assemblies
and namespaces - namespaces are merely a hierarchical way of organising type
names. To the runtime, type names are type names, regardless of whether
namespaces are used to organise the names. It's the assembly plus the typename
(regardless of whether the type name belongs to a namespace) that uniquely
indentifies a type to the runtime.
Assemblies are also important in .NET with respect to security - many of the
security restrictions are enforced at the assembly boundary.
Finally, assemblies are the unit of versioning in .NET - more on this below.
3.2 How can I produce an assembly?
The simplest way to produce an assembly is directly from a .NET compiler. For
example, the following C# program:
public class CTest
{
public CTest() { System.Console.WriteLine( "Hello from CTest" ); }
}
can be compiled into a library assembly (dll) like this:
csc /t:library ctest.cs
You can then view the contents of the assembly by running the "IL Disassembler"
tool that comes with the .NET SDK.
Alternatively you can compile your source into modules, and then combine the
modules into an assembly using the assembly linker (al.exe). For the C#
compiler, the /target:module switch is used to generate a module instead of an
assembly.
3.3 What is the difference between a private assembly and a shared assembly?
Location and visibility: A private assembly is normally used by a single
application, and is stored in the application's directory, or a sub-directory
beneath. A shared assembly is normally stored in the global assembly cache,
which is a repository of assemblies maintained by the .NET runtime. Shared
assemblies are usually libraries of code which many applications will find
useful, e.g. the .NET framework classes.
Versioning: The runtime enforces versioning constraints only on shared
assemblies, not on private assemblies.
3.4 How do assemblies find each other?
By searching directory paths. There are several factors which can affect the
path (such as the AppDomain host, and application configuration files), but for
private assemblies the search path is normally the application's directory and
its sub-directories. For shared assemblies, the search path is normally same as
the private assembly path plus the shared assembly cache.
3.5 How does assembly versioning work?
Each assembly has a version number called the compatibility version. Also each
reference to an assembly (from another assembly) includes both the name and
version of the referenced assembly.
The version number has four numeric parts (e.g. 5.5.2.33). Assemblies with
either of the first two parts different are normally viewed as incompatible. If
the first two parts are the same, but the third is different, the assemblies are
deemed as 'maybe compatible'. If only the fourth part is different, the
assemblies are deemed compatible. However, this is just the default guideline -
it is the version policy that decides to what extent these rules are enforced.
The version policy can be specified via the application configuration file.
Remember: versioning is only applied to shared assemblies, not private
assemblies.
3.6 How can I develop an application that automatically updates itself from the
web?
For .NET 1.x, use the Updater Application Block. For .NET 2.x, use ClickOnce.
4. Application Domains
4.1 What is an application domain?
An AppDomain can be thought of as a lightweight process. Multiple AppDomains can
exist inside a Win32 process. The primary purpose of the AppDomain is to isolate
applications from each other, and so it is particularly useful in hosting
scenarios such as ASP.NET. An AppDomain can be destroyed by the host without
affecting other AppDomains in the process.
Win32 processes provide isolation by having distinct memory address spaces. This
is effective, but expensive. The .NET runtime enforces AppDomain isolation by
keeping control over the use of memory - all memory in the AppDomain is managed
by the .NET runtime, so the runtime can ensure that AppDomains do not access
each other's memory.
One non-obvious use of AppDomains is for unloading types. Currently the only way
to unload a .NET type is to destroy the AppDomain it is loaded into. This is
particularly useful if you create and destroy types on-the-fly via reflection.
Microsoft have an AppDomain FAQ.
4.2 How does an AppDomain get created?
AppDomains are usually created by hosts. Examples of hosts are the Windows
Shell, ASP.NET and IE. When you run a .NET application from the command-line,
the host is the Shell. The Shell creates a new AppDomain for every application.
AppDomains can also be explicitly created by .NET applications. Here is a C#
sample which creates an AppDomain, creates an instance of an object inside it,
and then executes one of the object's methods:
using System;
using System.Runtime.Remoting;
using System.Reflection;
public class CAppDomainInfo : MarshalByRefObject
{
public string GetName() { return AppDomain.CurrentDomain.FriendlyName; }
}
public class App
{
public static int Main()
{
AppDomain ad = AppDomain.CreateDomain( "Andy's new domain" );
CAppDomainInfo adInfo = (CAppDomainInfo)ad.CreateInstanceAndUnwrap(
Assembly.GetCallingAssembly().GetName().Name, "CAppDomainInfo"
);
Console.WriteLine( "Created AppDomain name = " + adInfo.GetName() );
return 0;
}
}
4.3 Can I write my own .NET host?
Yes. For an example of how to do this, take a look at the source for the dm.net
moniker developed by Jason Whittington and Don Box. There is also a code sample
in the .NET SDK called CorHost.
5. Garbage Collection
5.1 What is garbage collection?
Garbage collection is a heap-management strategy where a run-time component
takes responsibility for managing the lifetime of the memory used by objects.
This concept is not new to .NET - Java and many other languages/runtimes have
used garbage collection for some time.
5.2 Is it true that objects don't always get destroyed immediately when the last
reference goes away?
Yes. The garbage collector offers no guarantees about the time when an object
will be destroyed and its memory reclaimed.
There was an interesting thread on the DOTNET list, started by Chris Sells,
about the implications of non-deterministic destruction of objects in C#. In
October 2000, Microsoft's Brian Harry posted a lengthy analysis of the problem.
Chris Sells' response to Brian's posting is here.
5.3 Why doesn't the .NET runtime offer deterministic destruction?
Because of the garbage collection algorithm. The .NET garbage collector works by
periodically running through a list of all the objects that are currently being
referenced by an application. All the objects that it doesn't find during this
search are ready to be destroyed and the memory reclaimed. The implication of
this algorithm is that the runtime doesn't get notified immediately when the
final reference on an object goes away - it only finds out during the next
'sweep' of the heap.
Futhermore, this type of algorithm works best by performing the garbage
collection sweep as rarely as possible. Normally heap exhaustion is the trigger
for a collection sweep.
5.4 Is the lack of deterministic destruction in .NET a problem?
It's certainly an issue that affects component design. If you have objects that
maintain expensive or scarce resources (e.g. database locks), you need to
provide some way to tell the object to release the resource when it is done.
Microsoft recommend that you provide a method called Dispose() for this purpose.
However, this causes problems for distributed objects - in a distributed system
who calls the Dispose() method? Some form of reference-counting or
ownership-management mechanism is needed to handle distributed objects -
unfortunately the runtime offers no help with this.
5.5 Should I implement Finalize on my class? Should I implement IDisposable?
This issue is a little more complex than it first appears. There are really two
categories of class that require deterministic destruction - the first category
manipulate unmanaged types directly, whereas the second category manipulate
managed types that require deterministic destruction. An example of the first
category is a class with an IntPtr member representing an OS file handle. An
example of the second category is a class with a System.IO.FileStream member.
For the first category, it makes sense to implement IDisposable and override
Finalize. This allows the object user to 'do the right thing' by calling
Dispose, but also provides a fallback of freeing the unmanaged resource in the
Finalizer, should the calling code fail in its duty. However this logic does not
apply to the second category of class, with only managed resources. In this case
implementing Finalize is pointless, as managed member objects cannot be accessed
in the Finalizer. This is because there is no guarantee about the ordering of
Finalizer execution. So only the Dispose method should be implemented. (If you
think about it, it doesn't really make sense to call Dispose on member objects
from a Finalizer anyway, as the member object's Finalizer will do the required
cleanup.)
For classes that need to implement IDisposable and override Finalize, see
Microsoft's documented pattern.
Note that some developers argue that implementing a Finalizer is always a bad
idea, as it hides a bug in your code (i.e. the lack of a Dispose call). A less
radical approach is to implement Finalize but include a Debug.Assert at the
start, thus signalling the problem in developer builds but allowing the cleanup
to occur in release builds.
5.6 Do I have any control over the garbage collection algorithm?
A little. For example the System.GC class exposes a Collect method, which forces
the garbage collector to collect all unreferenced objects immediately.
Also there is a gcConcurrent setting that can be specified via the application
configuration file. This specifies whether or not the garbage collector performs
some of its collection activities on a separate thread. The setting only applies
on multi-processor machines, and defaults to true.
5.7 How can I find out what the garbage collector is doing?
Lots of interesting statistics are exported from the .NET runtime via the '.NET
CLR xxx' performance counters. Use Performance Monitor to view them.
5.8 What is the lapsed listener problem?
The lapsed listener problem is one of the primary causes of leaks in .NET
applications. It occurs when a subscriber (or 'listener') signs up for a
publisher's event, but fails to unsubscribe. The failure to unsubscribe means
that the publisher maintains a reference to the subscriber as long as the
publisher is alive. For some publishers, this may be the duration of the
application.
This situation causes two problems. The obvious problem is the leakage of the
subscriber object. The other problem is the performance degredation due to the
publisher sending redundant notifications to 'zombie' subscribers.
There are at least a couple of solutions to the problem. The simplest is to make
sure the subscriber is unsubscribed from the publisher, typically by adding an
Unsubscribe() method to the subscriber. Another solution, documented here by
Shawn Van Ness, is to change the publisher to use weak references in its
subscriber list.
5.9 When do I need to use GC.KeepAlive?
It's very unintuitive, but the runtime can decide that an object is garbage much
sooner than you expect. More specifically, an object can become garbage while a
method is executing on the object, which is contrary to most developers'
expectations. Chris Brumme explains the issue on his blog. I've taken Chris's
code and expanded it into a full app that you can play with if you want to prove
to yourself that this is a real problem:
using System;
using System.Runtime.InteropServices;
class Win32
{
[DllImport("kernel32.dll")]
public static extern IntPtr CreateEvent( IntPtr lpEventAttributes,
bool bManualReset,bool bInitialState, string lpName);
[DllImport("kernel32.dll", SetLastError=true)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll")]
public static extern bool SetEvent(IntPtr hEvent);
}
class EventUser
{
public EventUser()
{
hEvent = Win32.CreateEvent( IntPtr.Zero, false, false, null );
}
~EventUser()
{
Win32.CloseHandle( hEvent );
Console.WriteLine("EventUser finalized");
}
public void UseEvent()
{
UseEventInStatic( this.hEvent );
}
static void UseEventInStatic( IntPtr hEvent )
{
//GC.Collect();
bool bSuccess = Win32.SetEvent( hEvent );
Console.WriteLine( "SetEvent " + (bSuccess ? "succeeded" :
"FAILED!") );
}
IntPtr hEvent;
}
class App
{
static void Main(string[] args)
{
EventUser eventUser = new EventUser();
eventUser.UseEvent();
}
}
If you run this code, it'll probably work fine, and you'll get the following
output:
SetEvent succeeded
EventDemo finalized
However, if you uncomment the GC.Collect() call in the UseEventInStatic()
method, you'll get this output:
EventDemo finalized
SetEvent FAILED!
(Note that you need to use a release build to reproduce this problem.)
So what's happening here? Well, at the point where UseEvent() calls
UseEventInStatic(), a copy is taken of the hEvent field, and there are no
further references to the EventUser object anywhere in the code. So as far as
the runtime is concerned, the EventUser object is garbage and can be collected.
Normally of course the collection won't happen immediately, so you'll get away
with it, but sooner or later a collection will occur at the wrong time, and your
app will fail.
A solution to this problem is to add a call to GC.KeepAlive(this) to the end of
the UseEvent method, as Chris explains.
6. Serialization
6.1 What is serialization?
Serialization is the process of converting an object into a stream of bytes.
Deserialization is the opposite process, i.e. creating an object from a stream
of bytes. Serialization/Deserialization is mostly used to transport objects
(e.g. during remoting), or to persist objects (e.g. to a file or database).
6.2 Does the .NET Framework have in-built support for serialization?
There are two separate mechanisms provided by the .NET class library -
XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer
for Web Services, and SoapFormatter/BinaryFormatter for remoting. Both are
available for use in your own code.
6.3 I want to serialize instances of my class. Should I use XmlSerializer,
SoapFormatter or BinaryFormatter?
It depends. XmlSerializer has severe limitations such as the requirement that
the target class has a parameterless constructor, and only public read/write
properties and fields can be serialized. However, on the plus side,
XmlSerializer has good support for customising the XML document that is produced
or consumed. XmlSerializer's features mean that it is most suitable for
cross-platform work, or for constructing objects from existing XML documents.
SoapFormatter and BinaryFormatter have fewer limitations than XmlSerializer.
They can serialize private fields, for example. However they both require that
the target class be marked with the [Serializable] attribute, so like
XmlSerializer the class needs to be written with serialization in mind. Also
there are some quirks to watch out for - for example on deserialization the
constructor of the new object is not invoked.
The choice between SoapFormatter and BinaryFormatter depends on the application.
BinaryFormatter makes sense where both serialization and deserialization will be
performed on the .NET platform and where performance is important. SoapFormatter
generally makes more sense in all other cases, for ease of debugging if nothing
else.
6.4 Can I customise the serialization process?
Yes. XmlSerializer supports a range of attributes that can be used to configure
serialization for a particular class. For example, a field or property can be
marked with the [XmlIgnore] attribute to exclude it from serialization. Another
example is the [XmlElement] attribute, which can be used to specify the XML
element name to be used for a particular property or field.
Serialization via SoapFormatter/BinaryFormatter can also be controlled to some
extent by attributes. For example, the [NonSerialized] attribute is the
equivalent of XmlSerializer's [XmlIgnore] attribute. Ultimate control of the
serialization process can be acheived by implementing the the ISerializable
interface on the class whose instances are to be serialized.
6.5 Why is XmlSerializer so slow?
There is a once-per-process-per-type overhead with XmlSerializer. So the first
time you serialize or deserialize an object of a given type in an application,
there is a significant delay. This normally doesn't matter, but it may mean, for
example, that XmlSerializer is a poor choice for loading configuration settings
during startup of a GUI application.
6.6 Why do I get errors when I try to serialize a Hashtable?
XmlSerializer will refuse to serialize instances of any class that implements
IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this
restriction.
6.7 XmlSerializer is throwing a generic "There was an error reflecting MyClass"
error. How do I find out what the problem is?
Look at the InnerException property of the exception that is thrown to get a
more specific error message.
6.8 Why am I getting an InvalidOperationException when I serialize an ArrayList?
XmlSerializer needs to know in advance what type of objects it will find in an
ArrayList. To specify the type, use the XmlArrayItem attibute like this:
public class Person
{
public string Name;
public int Age;
}
public class Population
{
[XmlArrayItem(typeof(Person))] public ArrayList People;
}
7. Attributes
7.1 What are attributes?
There are at least two types of .NET attribute. The first type I will refer to
as a metadata attribute - it allows some data to be attached to a class or
method. This data becomes part of the metadata for the class, and (like other
class metadata) can be accessed via reflection. An example of a metadata
attribute is [serializable], which can be attached to a class and means that
instances of the class can be serialized.
[serializable] public class CTest {}
The other type of attribute is a context attribute. Context attributes use a
similar syntax to metadata attributes but they are fundamentally different.
Context attributes provide an interception mechanism whereby instance activation
and method calls can be pre- and/or post-processed. If you have encountered
Keith Brown's universal delegator you'll be familiar with this idea.
7.2 Can I create my own metadata attributes?
Yes. Simply derive a class from System.Attribute and mark it with the
AttributeUsage attribute. For example:
[AttributeUsage(AttributeTargets.Class)]
public class InspiredByAttribute : System.Attribute
{
public string InspiredBy;
public InspiredByAttribute( string inspiredBy )
{
InspiredBy = inspiredBy;
}
}
[InspiredBy("Andy Mc's brilliant .NET FAQ")]
class CTest
{
}
class CApp
{
public static void Main()
{
object[] atts = typeof(CTest).GetCustomAttributes(true);
foreach( object att in atts )
if( att is InspiredByAttribute )
Console.WriteLine( "Class CTest was inspired by {0}", ((InspiredByAttribute)att).InspiredBy
);
}
}
7.3 Can I create my own context attibutes?
Yes. Take a look at Peter Drayton's Tracehook.NET.
8. Code Access Security
8.1 What is Code Access Security (CAS)?
CAS is the part of the .NET security model that determines whether or not code
is allowed to run, and what resources it can use when it is running. For
example, it is CAS that will prevent a .NET web applet from formatting your hard
disk.
8.2 How does CAS work?
The CAS security policy revolves around two key concepts - code groups and
permissions. Each .NET assembly is a member of a particular code group, and each
code group is granted the permissions specified in a named permission set.
For example, using the default security policy, a control downloaded from a web
site belongs to the 'Zone - Internet' code group, which adheres to the
permissions defined by the 'Internet' named permission set. (Naturally the
'Internet' named permission set represents a very restrictive range of
permissions.)
8.3 Who defines the CAS code groups?
Microsoft defines some default ones, but you can modify these and even create
your own. To see the code groups defined on your system, run 'caspol -lg' from
the command-line. On my system it looks like this:
Level = Machine
Code Groups:
1. All code: Nothing
1.1. Zone - MyComputer: FullTrust
1.1.1. Honor SkipVerification requests: SkipVerification
1.2. Zone - Intranet: LocalIntranet
1.3. Zone - Internet: Internet
1.4. Zone - Untrusted: Nothing
1.5. Zone - Trusted: Internet
1.6. StrongName -
0024000004800000940000000602000000240000525341310004000003
000000CFCB3291AA715FE99D40D49040336F9056D7886FED46775BC7BB5430BA4444FEF8348EBD06
F962F39776AE4DC3B7B04A7FE6F49F25F740423EBF2C0B89698D8D08AC48D69CED0FC8F83B465E08
07AC11EC1DCC7D054E807A43336DDE408A5393A48556123272CEEEE72F1660B71927D38561AABF5C
AC1DF1734633C602F8F2D5: Everything
Note the hierarchy of code groups - the top of the hierarchy is the most general
('All code'), which is then sub-divided into several groups, each of which in
turn can be sub-divided. Also note that (somewhat counter-intuitively) a
sub-group can be associated with a more permissive permission set than its
parent.
8.4 How do I define my own code group?
Use caspol. For example, suppose you trust code from
www.mydomain.com and you want it have
full access to your system, but you want to keep the default restrictions for
all other internet sites. To achieve this, you would add a new code group as a
sub-group of the 'Zone - Internet' group, like this:
caspol -ag 1.3 -site
www.mydomain.com FullTrust
Now if you run caspol -lg you will see that the new group has been added as
group 1.3.1:
...
1.3. Zone - Internet: Internet
1.3.1. Site -
www.mydomain.com: FullTrust
...
Note that the numeric label (1.3.1) is just a caspol invention to make the code
groups easy to manipulate from the command-line. The underlying runtime never
sees it.
8.5 How do I change the permission set for a code group?
Use caspol. If you are the machine administrator, you can operate at the
'machine' level - which means not only that the changes you make become the
default for the machine, but also that users cannot change the permissions to be
more permissive. If you are a normal (non-admin) user you can still modify the
permissions, but only to make them more restrictive. For example, to allow
intranet code to do what it likes you might do this:
caspol -cg 1.2 FullTrust
Note that because this is more permissive than the default policy (on a standard
system), you should only do this at the machine level - doing it at the user
level will have no effect.
8.6 Can I create my own permission set?
Yes. Use caspol -ap, specifying an XML file containing the permissions in the
permission set. To save you some time, here is a sample file corresponding to
the 'Everything' permission set - just edit to suit your needs. When you have
edited the sample, add it to the range of available permission sets like this:
caspol -ap samplepermset.xml
Then, to apply the permission set to a code group, do something like this:
caspol -cg 1.3 SamplePermSet
(By default, 1.3 is the 'Internet' code group)
8.7 I'm having some trouble with CAS. How can I troubleshoot the problem?
Caspol has a couple of options that might help. First, you can ask caspol to
tell you what code group an assembly belongs to, using caspol -rsg. Similarly,
you can ask what permissions are being applied to a particular assembly using
caspol -rsp.
8.8 I can't be bothered with CAS. Can I turn it off?
Yes, as long as you are an administrator. Just run:
caspol -s off