.NET Useful Guide

  1. Introduction

1.1 What is .NET?

That's difficult to sum up in a sentence. According to Microsoft, .NET is a "revolutionary new platform, built on open Internet protocols and standards, with tools and services that meld computing and communications in new ways".
A more practical definition would be that .NET is a new environment for developing and running software applications, featuring ease of development of web-based services, rich standard run-time services available to components written in a variety of programming languages, and inter-language and inter-machine interoperability.
Note that when the term ".NET" is used in this FAQ it refers only to the new .NET runtime and associated technologies. This is sometimes called the ".NET Framework". This FAQ does NOT cover any of the various other existing and new products/technologies that Microsoft are attaching the .NET name to (e.g. SQL Server.NET).

1.2 Does .NET only apply to people building web-sites?

No. If you write any Windows software (using ATL/COM, MFC, VB, or even raw Win32), .NET may offer a viable alternative (or addition) to the way you do things currently. Of course, if you do develop web sites, then .NET has lots to interest you - not least ASP.NET.

1.3 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.4 When was the first version of .NET released?

The final version of the 1.0 SDK and runtime was 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.

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

There are a number of tools, described here in ascending order of cost:
·         .NET Framework SDK: The SDK is free and includes command-line compilers for C++, C#, and VB.NET and various other utilities to aid development.
·         ASP.NET Web Matrix: This is a free ASP.NET development environment from Microsoft. As well as a GUI development environment, the download includes a simple web server that can be used instead of IIS to host ASP.NET apps. This opens up ASP.NET development to users of Windows XP Home Edition, which cannot run IIS.
·         Microsoft Visual C# .NET Standard 2003: This is a cheap (around $100) version of Visual Studio limited to one language and also with limited wizard support. For example, there's no wizard support for class libraries or custom UI controls. Useful for beginners to learn with, or for savvy developers who can work around the deficiencies in the supplied wizards. As well as C#, there are VB.NET and C++ versions.
·         Microsoft Visual Studio.NET Professional 2003: If you have a license for Visual Studio 6.0, you can get the upgrade. You can also upgrade from VS.NET 2002 for a token $30. Visual Studio.NET includes support for all the MS languages (C#, C++, VB.NET) and has extensive wizard support.
At the top end of the price spectrum are the Visual Studio.NET 2003 Enterprise and Enterprise Architect editions. These offer extra features such as Visual Sourcesafe (version control), and performance and analysis tools. Check out the Visual Studio.NET Feature Comparison at http://msdn.microsoft.com/vstudio/howtobuy/choosing.asp.

1.6 What platforms does the .NET Framework run on?

The runtime supports 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 Windows XP and Windows 2000. 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 Mono project is attempting to implement the .NET framework on Linux.

1.7 What languages does the .NET Framework support?

MS provides compilers for C#, C++, VB and JScript. Other vendors have announced that they intend to develop .NET compilers for languages such as COBOL, Eiffel, Perl, Smalltalk and Python.

1.8 Will the .NET Framework go through a standardisation process?

From http://msdn.microsoft.com/net/ecma/: "On December 13, 2001, the ECMA General Assembly ratified the C# and common language infrastructure (CLI) specifications into international standards. The ECMA standards will be known as ECMA-334 (C#) and ECMA-335 (the CLI)."

2. Basic terminology

2.1 What is the CLR?

CLR = Common Language Runtime. The CLR is a set of standard resources that (in theory) any .NET program can take advantage of, regardless of programming language. Robert Schmidt (Microsoft) lists the following CLR resources in his MSDN PDC# article:
·         Object-oriented programming model (inheritance, polymorphism, exception handling, garbage collection)
·         Security model
·         Type system
·         All .NET base classes
·         Many .NET framework classes
·         Development, debugging, and profiling tools
·         Execution and code management
·         IL-to-native translators and optimizers
What this means is that in the .NET world, different programming languages will be more equal in capability than they have ever been before, although clearly not all languages will support all CLR services.

2.2 What is the CTS?

CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that .NET applications can use. However note that not all .NET languages will support all the types in the CTS. The CTS is a superset of the CLS.

2.3 What is the CLS?

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.
In theory this allows very tight interop between different .NET languages - for example allowing a C# class to inherit from a VB class.

2.4 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. The IL is then converted to machine code at the point where the software is installed, or at run-time by a Just-In-Time (JIT) compiler.

2.5 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.6 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. All C# and Visual Basic.NET code is managed by default. VS7 C++ code is not managed by default, but the compiler can produce managed code by specifying a command-line switch (/com+).
Managed data: This is data that is allocated and de-allocated by the .NET runtime's garbage collector. C# and VB.NET data is always managed. VS7 C++ data is unmanaged by default, even when using the /com+ switch, but it can be marked as managed using the __gc keyword.
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.7 What is reflection?

All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System.Reflection namespace contains classes that can be used to interrogate the types for a module/assembly.
Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshaling data across context/process/machine boundaries.
Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder).

3. Assemblies

3.1 What is an assembly?

An assembly is sometimes described as a logical .EXE or .DLL, and can be an application (with a main entry point) or a library. An assembly consists of one or more files (dlls, exes, html files etc), and represents a group of resources, type definitions, and implementations of those types. An assembly may also contain references to other assemblies. These resources, types and references are described in a block of data called a manifest. The manifest is part of the assembly, thus making the assembly self-describing.
An important aspect of assemblies is that they are part of the identity of a type. The identity of a type is the assembly that houses it combined with the type name. This means, for example, that if assembly A exports a type called T, and assembly B exports a type called T, the .NET runtime sees these as two completely different types. Furthermore, don't get confused between assemblies and namespaces - namespaces are merely a hierarchical way of organising type names. To the runtime, type names are type names, regardless of whether namespaces are used to organise the names. It's the assembly plus the typename (regardless of whether the type name belongs to a namespace) that uniquely indentifies a type to the runtime.
Assemblies are also important in .NET with respect to security - many of the security restrictions are enforced at the assembly boundary.
Finally, assemblies are the unit of versioning in .NET - more on this below.

3.2 How can I produce an assembly?

The simplest way to produce an assembly is directly from a .NET compiler. For example, the following C# program:
public class CTest
{
       public CTest()
       {
               System.Console.WriteLine( "Hello from CTest" );
       }
}
can be compiled into a library assembly (dll) like this:
csc /t:library ctest.cs
You can then view the contents of the assembly by running the "IL Disassembler" tool that comes with the .NET SDK.
Alternatively you can compile your source into modules, and then combine the modules into an assembly using the assembly linker (al.exe). For the C# compiler, the /target:module switch is used to generate a module instead of an assembly.

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

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

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 an application from other applications.
Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. 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.

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. Note that you must name the executable 'appdomaintest.exe' for this code to work as-is.
using System;
using System.Runtime.Remoting;
 
public class CAppDomainInfo : MarshalByRefObject
{
       public string GetAppDomainInfo()
       {
               return "AppDomain = " + AppDomain.CurrentDomain.FriendlyName;
       }
 
}
 
public class App
{
    public static int Main()
    {
               AppDomain ad = AppDomain.CreateDomain( "Andy's new domain", null, null );
               ObjectHandle oh = ad.CreateInstance( "appdomaintest", "CAppDomainInfo" );
               CAppDomainInfo adInfo = (CAppDomainInfo)(oh.Unwrap());
               string info = adInfo.GetAppDomainInfo();
               
               Console.WriteLine( "AppDomain info: " + info );
               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 (http://staff.develop.com/jasonw/clr/readme.htm ). 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 system whereby a run-time component takes responsibility for managing the lifetime of objects and the heap memory that they occupy. 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 is an interesting thread in the archives, started by Chris Sells, about the implications of non-deterministic destruction of objects in C#: http://discuss.develop.com/archives/wa.exe?A2=ind0007&L=DOTNET&P=R24819
In October 2000, Microsoft's Brian Harry posted a lengthy analysis of the problem: http://discuss.develop.com/archives/wa.exe?A2=ind0010A&L=DOTNET&P=R28572
Chris Sells' response to Brian's posting is here: http://discuss.develop.com/archives/wa.exe?A2=ind0010C&L=DOTNET&P=R983

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 for the client 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 Does non-deterministic destruction affect the usage of COM objects from managed code?

Yes. When using a COM object from managed code, you are effectively relying on the garbage collector to call the final release on your object. If your COM object holds onto an expensive resource which is only cleaned-up after the final release, you may need to provide a new interface on your object which supports an explicit Dispose() method.

5.6 I've heard that Finalize methods should be avoided. Should I implement Finalize on my class?

An object with a Finalize method is more work for the garbage collector than an object without one. Also there are no guarantees about the order in which objects are Finalized, so there are issues surrounding access to other objects from the Finalize method. Finally, there is no guarantee that a Finalize method will get called on an object, so it should never be relied upon to do clean-up of an object's resources.
Microsoft recommend the following pattern:
public class CTest : IDisposable
{ 
       public void Dispose()
       {
               ... // Cleanup activities
               GC.SuppressFinalize(this); 
       } 
 
       ~CTest()       // C# syntax hiding the Finalize() method
       {
               Dispose(); 
       }
}
In the normal case the client calls Dispose(), the object's resources are freed, and the garbage collector is relieved of its Finalizing duties by the call to SuppressFinalize(). In the worst case, i.e. the client forgets to call Dispose(), there is a reasonable chance that the object's resources will eventually get freed by the garbage collector calling Finalize(). Given the limitations of the garbage collection algorithm this seems like a pretty reasonable approach.

5.7 Do I have any control over the garbage collection algorithm?

A little. For example, the System.GC class exposes a Collect method - this forces the garbage collector to collect all unreferenced objects immediately.

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

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 of 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 uses 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.

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've come across 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 attributes?

Yes. Take a look at Don Box's sample (called CallThreshold) at http://www.develop.com/dbox/dotnet/threshold/, and also Peter Drayton's Tracehook.NET at http://www.razorsoft.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 a piece of 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 diagnose my 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 all this CAS stuff. Can I turn it off?

Yes, as long as you are an administrator. Just run:
caspol -s off

9. Intermediate Language (IL)

9.1 Can I look at the IL for an assembly?

Yes. MS supply a tool called Ildasm which can be used to view the metadata and IL for an assembly.

9.2 Can source code be reverse-engineered from IL?

Yes, it is often relatively straightforward to regenerate high-level source (e.g. C#) from IL.

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

You can buy an IL obfuscation tool. These tools work by 'optimising' the IL in such a way that reverse-engineering becomes much more difficult.
Of course if you are writing web services then reverse-engineering is not a problem as clients do not have access to your IL.

9.4 Can I write IL programs directly?

Yes. Peter Drayton posted this simple example to the DOTNET mailing list:
.assembly MyAssembly {}
.class MyApp {
  .method static void Main() {
    .entrypoint
    ldstr      "Hello, IL!"
    call       void System.Console::WriteLine(class System.Object)
    ret
  }
}
Just put this into a file called hello.il, and then run ilasm hello.il. An exe assembly will be generated.

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

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

10. Implications for COM

10.1 Is COM dead?

This subject causes a lot of controversy, as you'll see if you read the mailing list archives. Take a look at the following two threads:
FWIW my view is as follows: COM is many things, and it's different things to different people. But to me, COM is fundamentally about how little blobs of code find other little blobs of code, and how they communicate with each other when they find each other. COM specifies precisely how this location and communication takes place. In a 'pure' .NET world, consisting entirely of .NET objects, little blobs of code still find each other and talk to each other, but they don't use COM to do so. They use a model which is similar to COM in some ways - for example, type information is stored in a tabular form packaged with the component, which is quite similar to packaging a type library with a COM component. But it's not COM.
So, does this matter? Well, I don't really care about most of the COM stuff going away - I don't care that finding components doesn't involve a trip to the registry, or that I don't use IDL to define my interfaces. But there is one thing that I wouldn't like to go away - I wouldn't like to lose the idea of interface-based development. COM's greatest strength, in my opinion, is its insistence on a cast-iron separation between interface and implementation. Unfortunately, the .NET framework seems to make no such insistence - it lets you do interface-based development, but it doesn't insist. Some people would argue that having a choice can never be a bad thing, and maybe they're right, but I can't help feeling that maybe it's a backward step.

10.2 Is DCOM dead?

Pretty much, for .NET developers. The .NET Framework has a new remoting model which is not based on DCOM. Of course DCOM will still be used in interop scenarios.

10.3 Is MTS/COM+ dead?

No. The approach for the first .NET release is to provide access to the existing COM+ services (through an interop layer) rather than replace the services with native .NET ones. Various tools and attributes are provided to try to make this as painless as possible. The PDC release of the .NET SDK includes interop support for core services (JIT activation, transactions) but not some of the higher level services (e.g. COM+ Events, Queued components).
Over time it is expected that interop will become more seamless - this may mean that some services become a core part of the CLR, and/or it may mean that some services will be rewritten as managed code which runs on top of the CLR.
For more on this topic, search for postings by Joe Long in the archives - Joe is the MS group manager for COM+. Start with this message:

10.4 Can I use COM components from .NET programs?

Yes. COM components are accessed from the .NET runtime via a Runtime Callable Wrapper (RCW). This wrapper turns the COM interfaces exposed by the COM component into .NET-compatible interfaces. For oleautomation interfaces, the RCW can be generated automatically from a type library. For non-oleautomation interfaces, it may be necessary to develop a custom RCW which manually maps the types exposed by the COM interface to .NET-compatible types.
Here's a simple example for those familiar with ATL. First, create an ATL component which implements the following IDL:
import "oaidl.idl"; 
import "ocidl.idl";
 
[
       object,
       uuid(EA013F93-487A-4403-86EC-FD9FEE5E6206),
       helpstring("ICppName Interface"), 
       pointer_default(unique), 
       oleautomation
] 
 
interface ICppName : IUnknown
{ 
       [helpstring("method SetName")] HRESULT SetName([in] BSTR name); 
       [helpstring("method GetName")] HRESULT GetName([out,retval] BSTR *pName ); 
}; 
 
[ 
       uuid(F5E4C61D-D93A-4295-A4B4-2453D4A4484D), 
       version(1.0),
       helpstring("cppcomserver 1.0 Type Library")
] 
library CPPCOMSERVERLib 
{
       importlib("stdole32.tlb");
       importlib("stdole2.tlb"); 
       [
               uuid(600CE6D9-5ED7-4B4D-BB49-E8D5D5096F70),  
               helpstring("CppName Class") 
       ]
       coclass CppName
       { 
               [default] interface ICppName; 
       };
};
When you've built the component, you should get a typelibrary. Run the TLBIMP utility on the typelibary, like this:
tlbimp cppcomserver.tlb
If successful, you will get a message like this:
Typelib imported successfully to CPPCOMSERVERLib.dll
You now need a .NET client - let's use C#. Create a .cs file containing the following code:
using System;
using CPPCOMSERVERLib; 
 
public class MainApp 
{ 
       static public void Main() 
       { 
               CppName cppname = new CppName();
               cppname.SetName( "bob" ); 
               Console.WriteLine( "Name is " + cppname.GetName() ); 
       }
}
Note that we are using the type library name as a namespace, and the COM class name as the class. Alternatively we could have used CPPCOMSERVERLib.CppName for the class name and gone without the using CPPCOMSERVERLib statement.
Compile the C# code like this:
csc /r:cppcomserverlib.dll csharpcomclient.cs
Note that the compiler is being told to reference the DLL we previously generated from the typelibrary using TLBIMP.
You should now be able to run csharpcomclient.exe, and get the following output on the console:
Name is bob

10.5 Can I use .NET components from COM programs?

Yes. .NET components are accessed from COM via a COM Callable Wrapper (CCW). This is similar to a RCW (see previous question), but works in the opposite direction. Again, if the wrapper cannot be automatically generated by the .NET development tools, or if the automatic behaviour is not desirable, a custom CCW can be developed. Also, for COM to 'see' the .NET component, the .NET component must be registered in the registry.
Here's a simple example. Create a C# file called testcomserver.cs and put the following in it:
          
using System; 
using System.Runtime.InteropServices;
 
namespace AndyMc 
{ 
       [ClassInterface(ClassInterfaceType.AutoDual)]
       public class CSharpCOMServer
       { 
               public CSharpCOMServer() {} 
               public void SetName( string name ) { m_name = name; } 
               public string GetName() { return m_name; }  
               private string m_name; 
       }          
}
Then compile the .cs file as follows:
csc /target:library testcomserver.cs
You should get a dll, which you register like this:
regasm testcomserver.dll /tlb:testcomserver.tlb /codebase
Now you need to create a client to test your .NET COM component. VBScript will do - put the following in a file called comclient.vbs:
Dim dotNetObj 
Set dotNetObj = CreateObject("AndyMc.CSharpCOMServer") 
dotNetObj.SetName ("bob") 
MsgBox "Name is " & dotNetObj.GetName()
and run the script like this:
wscript comclient.vbs
And hey presto you should get a message box displayed with the text "Name is bob".
An alternative to the approach above it to use the dm.net moniker developed by Jason Whittington and Don Box. Go to http://staff.develop.com/jasonw/clr/readme.htm to check it out.

10.6 Is ATL redundant in the .NET world?

Yes, if you are writing applications that live inside the .NET framework. Of course many developers may wish to continue using ATL to write C++ COM components that live outside the framework, but if you are inside you will almost certainly want to use C#. Raw C++ (and therefore ATL which is based on it) doesn't have much of a place in the .NET world - it's just too near the metal and provides too much flexibility for the runtime to be able to manage it.

11. Miscellaneous

11.1 How does .NET remoting work?

.NET remoting involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is intended for LANs only - HTTP can be used for LANs or WANs (internet).
Support is provided for multiple message serializarion formats. Examples are SOAP (XML-based) and binary. By default, the HTTP channel uses SOAP (via the .NET runtime Serialization SOAP Formatter), and the TCP channel uses binary (via the .NET runtime Serialization Binary Formatter). But either channel can use either serialization format.
There are a number of styles of remote access:
·         SingleCall. Each incoming request from a client is serviced by a new object. The object is thrown away when the request has finished.
 
·         Singleton. All incoming requests from clients are processed by a single server object.
 
·         Client-activated object. This is the old stateful (D)COM model whereby the client receives a reference to the remote object and holds that reference (thus keeping the remote object alive) until it is finished with it.
Distributed garbage collection of objects is managed by a system called 'leased based lifetime'. Each object has a lease time, and when that time expires the object is disconnected from the .NET runtime remoting infrastructure. Objects have a default renew time - the lease is renewed when a successful call is made from the client to the object. The client can also explicitly renew the lease.
If you're interested in using XML-RPC as an alternative to SOAP, take a look at Charles Cook's XML-RPC.Net site at http://www.cookcomputing.com/xmlrpc/xmlrpc.shtml.

11.2 How can I get at the Win32 API from a .NET program?

Use P/Invoke. This uses similar technology to COM Interop, but is used to access static DLL entry points instead of COM objects. Here is an example of C# calling the Win32 MessageBox function:
using System; 
using System.Runtime.InteropServices; 
 
class MainApp 
{ 
       [DllImport("user32.dll", EntryPoint="MessageBox", SetLastError=true, CharSet=CharSet.Auto)]        
       public static extern int MessageBox(int hWnd, String strMessage, String strCaption, uint uiType);
       
       public static void Main() 
       {
               MessageBox( 0, "Hello, this is PInvoke in operation!", ".NET", 0 ); 
       }
}        

11.3 How do I write to the application configuration file at runtime?

12. Class Library

12.1 File I/O

12.1.1 How do I read from a text file?

First, use a System.IO.FileStream object to open the file:
FileStream fs = new FileStream( @"c:\test.txt", FileMode.Open, FileAccess.Read );
FileStream inherits from Stream, so you can wrap the FileStream object with a StreamReader object. This provides a nice interface for processing the stream line by line:
StreamReader sr = new StreamReader( fs );
string curLine;
while( (curLine = sr.ReadLine()) != null )
       Console.WriteLine( curLine );
Finally close the StreamReader object:
sr.Close();
Note that this will automatically call Close() on the underlying Stream object, so an explicit fs.Close() is not required.

12.1.2 How do I write to a text file?

Similar to the read example, except use StreamWriter instead of StreamReader.

12.1.3 How do I read/write binary files?

Similar to text files, except wrap the FileStream object with a BinaryReader/Writer object instead of a StreamReader/Writer object.

12.2 Text Processing

12.2.1 Are regular expressions supported?

Yes. Use the System.Text.RegularExpressions.Regex class. For example, the following code updates the title in an HTML file:
FileStream fs = new FileStream( "test.htm", FileMode.Open, FileAccess.Read );
StreamReader sr = new StreamReader( fs ); 
               
Regex r = new Regex( "<TITLE>(.*)</TITLE>" ); 
string s; 
while( (s = sr.ReadLine()) != null ) 
{
       if( r.IsMatch( s ) )  
               s = r.Replace( s, "<TITLE>New and improved ${1}</TITLE>" );
       Console.WriteLine( s ); 
}

12.3 Internet

12.3.1 How do I download a web page?

First use the System.Net.WebRequestFactory class to acquire a WebRequest object:
WebRequest request = WebRequest.Create( "http://localhost" );
Then ask for the response from the request:
WebResponse response = request.GetResponse();
The GetResponse method blocks until the download is complete. Then you can access the response stream like this:
Stream s = response.GetResponseStream();
 
// Output the downloaded stream to the console
StreamReader sr = new StreamReader( s );
string line;
while( (line = sr.ReadLine()) != null )
       Console.WriteLine( line );
Note that WebRequest and WebReponse objects can be downcast to HttpWebRequest and HttpWebReponse objects respectively, to access http-specific functionality.

12.3.2 How do I use a proxy?

Two approaches - to affect all web requests do this:
System.Net.GlobalProxySelection.Select = new WebProxy( "proxyname", 80 );
Alternatively, to set the proxy for a specific web request, do this:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create( "http://localhost" );
request.Proxy = new WebProxy( "proxyname", 80 );

12.4 XML

12.4.1 Is DOM supported?

Yes. Take this example XML document:
<PEOPLE>
       <PERSON>Fred</PERSON>
       <PERSON>Bill</PERSON>  
</PEOPLE>      
This document can be parsed as follows:
XmlDocument doc = new XmlDocument();
doc.Load( "test.xml" );
 
XmlNode root = doc.DocumentElement;
 
foreach( XmlNode personElement in root.ChildNodes )
       Console.WriteLine( personElement.FirstChild.Value.ToString() );
The output is:
Fred
Bill

12.4.2 Is SAX supported?

No. Instead, a new XmlReader/XmlWriter API is offered. Like SAX it is stream-based but it uses a 'pull' model rather than SAX's 'push' model. Here's an example:
XmlTextReader reader = new XmlTextReader( "test.xml" );
 
while( reader.Read() )
{
       if( reader.NodeType == XmlNodeType.Element && reader.Name == "PERSON" )
       {
               reader.Read(); // Skip to the child text
               Console.WriteLine( reader.Value );
       }
}

12.4.3 Is XPath supported?

Yes, via the XPathXXX classes:
XPathDocument xpdoc = new XPathDocument("test.xml");
XPathNavigator nav = xpdoc.CreateNavigator();
XPathExpression expr = nav.Compile("descendant::PEOPLE/PERSON");
 
XPathNodeIterator iterator = nav.Select(expr);
while (iterator.MoveNext())
       Console.WriteLine(iterator.Current);

12.5 Threading

12.5.1 Is multi-threading supported?

Yes, there is extensive support for multi-threading. New threads can be spawned, and there is a system-provided threadpool which applications can use.

12.5.2 How do I spawn a thread?

Create an instance of a System.Threading.Thread object, passing it an instance of a ThreadStart delegate that will be executed on the new thread. For example:
class MyThread
{
       public MyThread( string initData )
       {
               m_data = initData;
               m_thread = new Thread( new ThreadStart(ThreadMain) ); 
               m_thread.Start();      
       }
 
       // ThreadMain() is executed on the new thread.
       private void ThreadMain()
       {
               Console.WriteLine( m_data );
       }
 
       public void WaitUntilFinished()
       {
               m_thread.Join();
       }       
 
       private Thread m_thread;
       private string m_data;
}
In this case creating an instance of the MyThread class is sufficient to spawn the thread and execute the MyThread.ThreadMain() method:
MyThread t = new MyThread( "Hello, world." );
t.WaitUntilFinished();

12.5.3 How do I stop a thread?

There are several options. First, you can use your own communication mechanism to tell the ThreadStart method to finish. Alternatively the Thread class has in-built support for instructing the thread to stop. The two principle methods are Thread.Interrupt() and Thread.Abort(). The former will cause a ThreadInterruptedException to be thrown on the thread when it next goes into a WaitJoinSleep state. In other words, Thread.Interrupt is a polite way of asking the thread to stop when it is no longer doing any useful work. In contrast, Thread.Abort() throws a ThreadAbortException regardless of what the thread is doing. Furthermore, the ThreadAbortException cannot normally be caught (though the ThreadStart's finally method will be executed). Thread.Abort() is a heavy-handed mechanism which should not normally be required.

12.5.4 How do I use the thread pool?

By passing an instance of a WaitCallback delegate to the ThreadPool.QueueUserWorkItem() method:
class CApp
{
       static void Main()
       {
               string s = "Hello, World";
               ThreadPool.QueueUserWorkItem( new WaitCallback( DoWork ), s );
               
               Thread.Sleep( 1000 );  // Give time for work item to be executed
       }
 
       // DoWork is executed on a thread from the thread pool.
       static void DoWork( object state )
       {
               Console.WriteLine( state );
       }
}

12.5.5 How do I know when my thread pool work item has completed?

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

12.5.6 How do I prevent concurrent access to my data?

Each object has a concurrency lock (critical section) associated with it. The System.Threading.Monitor.Enter/Exit methods are used to acquire and release this lock. For example, instances of the following class only allow one thread at a time to enter method f():
class C
{
       public void f()
       {
               try
               {
                       Monitor.Enter(this);
                       ...
               }
               finally
               {
                       Monitor.Exit(this);
               }
       }
}
C# has a 'lock' keyword which provides a convenient shorthand for the code above:
class C
{
       public void f()
       {
               lock(this)
               {
                       ...
               }
       }
}
Note that calling Monitor.Enter(myObject) does NOT mean that all access to myObject is serialized. It means that the synchronisation lock associated with myObject has been acquired, and no other thread can acquire that lock until Monitor.Exit(o) is called. In other words, this class is functionally equivalent to the classes above:
class C
{
       public void f()
       {
               lock( m_object )
               {
                       ...
               }
       }
       
       private m_object = new object();
}

12.6 Tracing

12.6.1 Is there built-in support for tracing/logging?

Yes, in the System.Diagnostics namespace. There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.

12.6.2 Can I redirect tracing to a file?

Yes. The Debug and Trace classes both have a Listeners property, which is a collection of sinks that receive the tracing that you send via Debug.WriteLine and Trace.WriteLine respectively. By default the Listeners collection contains a single sink, which is an instance of the DefaultTraceListener class. This sends output to the Win32 OutputDebugString() function and also the System.Diagnostics.Debugger.Log() method. This is useful when debugging, but if you're trying to trace a problem at a customer site, redirecting the output to a file is more appropriate. Fortunately, the TextWriterTraceListener class is provided for this purpose.
Here's how to use the TextWriterTraceListener class to redirect Trace output to a file:
Trace.Listeners.Clear();
FileStream fs = new FileStream( @"c:\log.txt", FileMode.Create, FileAccess.Write );
Trace.Listeners.Add( new TextWriterTraceListener( fs ) );
 
Trace.WriteLine( @"This will be writen to c:\log.txt!" );
Trace.Flush();
Note the use of Trace.Listeners.Clear() to remove the default listener. If you don't do this, the output will go to the file and OutputDebugString(). Typically this is not what you want, because OutputDebugString() imposes a big performance hit.

12.6.3 Can I customise the trace output?

Yes. You can write your own TraceListener-derived class, and direct all output through it. Here's a simple example, which derives from TextWriterTraceListener (and therefore has in-built support for writing to files, as shown above) and adds timing information and the thread ID for each trace line:
class MyListener : TextWriterTraceListener
{
       public MyListener( Stream s ) : base(s)
       {
       }
 
       public override void WriteLine( string s )
       {
               Writer.WriteLine( "{0:D8} [{1:D4}] {2}", 
                       Environment.TickCount - m_startTickCount, 
                       AppDomain.GetCurrentThreadId(),
                       s );
       }
 
       protected int m_startTickCount = Environment.TickCount;
}
(Note that this implementation is not complete - the TraceListener.Write method is not overridden for example.)
The beauty of this approach is that when an instance of MyListener is added to the Trace.Listeners collection, all calls to Trace.WriteLine() go through MyListener, including calls made by referenced assemblies that know nothing about the MyListener class.

13. Resources

13.1 Recommended books

I recommend the following books, either because I personally like them, or because I think they are well regarded by other .NET developers. (Note that I get a commission from Amazon if you buy a book after following one of these links.)
·         Applied Microsoft .NET Framework Programming - Jeffrey Richter
Much anticipated, mainly due to Richter's superb Win32 books, and most people think it delivers. The 'applied' is a little misleading - this book is mostly about how the .NET Framework works 'under the hood'. Examples are in C#, but there is also a separate
VB edition of the book.
 
·         Essential .NET Volume 1, The Common Language Runtime - Don Box
A superb book, which I recommend to anyone who already has some .NET development experience, and wants to get a deeper understanding of CLR fundamentals. It's clear that Box has deeply researched the topics and then carefully constructed a coherent story around his findings. It's rare to find such 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 including Windows Forms, COM interop, ADO.NET, ASP.NET etc. Troelsen also has a respected VB.NET book called
Visual Basic .NET and the .NET Platform: 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, without offering 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 worth reading.
 
·         Developing Applications with Visual Studio.NET - Richard Grimes
Covers lots of interesting topics that other books don't, including ATL7, Managed C++, internationalization, remoting, as well as the more run-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 Visual Basic .NET - Francesco Balena
Balena is a reknowned VB-er, and the reviews of his VB.NET book are glowing.
 
·         .NET and COM - The Complete Interoperability Guide - Adam Nathan
Don't be put off by the size - this book is very easy to digest thanks to the superb writing style. The bible of .NET/COM interop.
 
·         Advanced .NET Remoting - Ingo Rammer
Widely recommended.
 

13.2 Internet Resources

·         The Microsoft .NET homepage is at http://www.microsoft.com/net/. Microsoft also host GOTDOTNET.
·         DevX host the .NET Zone.
·         http://www.cetus-links.org/oo_dotnet.html is a superb set of links to .NET resources.
·         Chris Sells has a great set of .NET links at http://www.sellsbrothers.com/links/#manlinks.
·         CSharp.org
·         microsoft.public.dotnet.* newsgroups
·         My C# FAQ for C++ Programmers.

13.3 Weblogs

The following Weblogs ('blogs') have regular .NET content:
·         The .NET Guy (Brad Wilson)
·         Charles Cook: Developer of XML-RPC.NET.
·         Gwyn Cole: Co-author of Developing WMI solutions.
·         Chris Brumme
·         Brad Abrams
·         Don Box
·         John Lam
·         Peter Drayton: Co-author of C# Essentials and C# in a Nutshell.
·         Ingo Rammer: Author of Advanced .NET remoting.
·         Drew Marsh
·         Tomas Restrepo
·         Justin Rudd
·         Simon Fell: Developer of PocketSOAP.
·         Richard Caetano
·         Chris Sells

13.4 Sample code & utilities

Lutz Roeder has some great utilities and libraries at http://www.aisto.com/roeder/dotnet/
Peter Drayton's .NET Goodies page is at http://www.razorsoft.net/
Don Box & Jason Whittington's dm.net COM moniker at http://staff.develop.com/jasonw/clr/readme.htm
Mike Woodring has some .NET samples at http://staff.develop.com/woodring/dotnet/
Charles Cook's XML-RPC.Net library is available at http://www.cookcomputing.com/.


Basic .NET Framework questions

1) What is IL? (What is MSIL or CIL, What is JIT?)
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.

2) What is the CLR?
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)

3) What is the 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.

4) What is CLS (Common Language Specification)?
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.

5) What is Managed Code?
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. Managed data—data that is allocated and de-allocated by the common language runtime's garbage collector.

6) What is Assembly?
Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly.

7) What are different types of Assemblies?
Single file and multi file assembly. Assemblies can be static or dynamic. Private assemblies and shared assemblies

8) What is Namespace?
A namespace is a logical naming scheme for types in which a simple type name a
9) What is Difference between Namespace and Assembly?
Namespace is a logical design-time naming convenience, whereas an assembly establishes the name scope for types at run time.

10) If you want to view a Assembly how to you go about it (: What is ILDASM ?)?
You can use the MSIL Disassembler (Ildasm.exe) to view Microsoft intermediate language (MSIL) information in a file. If the file being examined is an assembly, this information can include the assembly's attributes, as well as references to other modules and assemblies. This information can be helpful in determining whether a file is an assembly or part of an assembly, and whether the file has references to other modules or assemblies. To view assembly contents
At the command prompt, type the following command: Ildasm <assembly name>
In this command, assembly name is the name of the assembly to examine.
11) What is Manifest?
Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information.

12) Where is version information stored of an assembly? The version number is stored in the assembly manifest along with other identity information, including the assembly name and public key, as well as information on relationships and identities of other assemblies connected with the application.

13) Is versioning applicable to private assemblies?

14) What is GAC (What are situations when you register .NET assembly in GAC?)?
Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. There are several ways to deploy an assembly into the global assembly cache: 1)Use an installer designed to work with the global assembly cache. This is the preferred option for installing assemblies into the global assembly cache. 2) Use a developer tool called the Global Assembly Cache tool (Gacutil.exe) provided by the .NET Framework SDK. 3) Use Windows Explorer to drag assemblies into the cache.
15) What is concept of strong names (How do we generate strong names or what is the process of generating strong names, What is use of SN.EXE, How do we apply strong names to assembly? How do you sign an assembly?)?
A strong name consists of the assembly's identity — its simple text name, version number, and culture information (if provided) — plus a public key and a digital signature. It is generated from an assembly file using the corresponding private key. (The assembly file contains the assembly manifest, which contains the names and hashes of all the files that make up the assembly.)
There are two ways to sign an assembly with a strong name:
1) Using the Assembly Linker (Al.exe) provided by the .NET Framework SDK.
2) Using assembly attributes to insert the strong name information in your code. U can use either the AssemblyKeyFileAttribute or the AssemblyKeyNameAttribute,
depending on where the key file to be used is located.

16) How to add and remove an assembly from GAC?
The gacutil.exe that ships with .NET can be used to add or remove a shared assembly from the GAC. To add a shared assembly, from the command line enter: gacutil.exe/i myassembly.dll. To remove from shared assembly: gacutil.exe /u myassembly.dll                    

17) What is Delay signing?
Delay signing allows a developer to add the public key token to an assembly, without having access to the private key token.

18) What is garbage collector?
The garbage collector's job is to identify objects that are no longer in use and reclaim the memory. What does it mean for an object to be in use?

19) Can we force garbage collector to run?
Garbage collector works automatically and you cannot force the garbage collector to run.

20) What is reflection?
Reflection is the mechanism of discovering class information solely at run time
22) What are Value types and Reference types?
Reference types are stored on the run-time heap; they may only be accessed through a reference to that storage. Because reference types are always accessed through references, their lifetime is managed by the .NET Framework Value types are stored directly on the stack, either within an array or within another type; their storage can only be accessed directly. Because value types are stored directly within variables, their lifetime is determined by the lifetime of the variable that contains them

23) What is concept of Boxing and Unboxing?
Boxing and unboxing is a essential concept in. NET’s type system. With Boxing and unboxing one can link between value-types and reference-types by allowing any value of a value-type to be converted to and from type object. Boxing and unboxing enables a unified view of the type system wherein a value of any type can ultimately be treated as an object. Converting a value type to reference type is called Boxing. Unboxing is the opposite operation and is an explicit operation.

24) What’s difference between VB.NET and C#?
Although differences exist between Visual Basic .NET and Visual C# .NET, they are both first-class programming languages that are based on the Microsoft® .NET Framework, and they are equally powerful..."

25) What is CODE Access security? Code access security is a mechanism that helps limit the access code has to protected resources and operations. In the .NET Framework *Primitive: Data types that can be mapped directly to the .NET Framework Class Library (FCL) types are called Primitive. For example, the type "int" is mapped to System.Int32, "short" is mapped to System.Int16, and so on. In fact, all data types in .NET are derived from the System.Object class. The following two classes are equivalent (in C#):
// Class implicitly derives from System.Object   Class Car{};Class Car{};// Class explicitly derives from System.Object              Class Car: System.Object{};


NET Interoperability
1) How can we use COM Components in .NET (What is RCW)?
Whenever managed client calls a method on a COM object, the runtime creates a runtime callable wrapper (RCW). NET components can call COM components. COM components can call .NET components. One tool for performing this conversion is called tlbimp (type library importer), and it is provided as part of the .NET Framework Software Developer Kit (SDK). Tlbimp reads the metadata from a COM type library and creates a matching CLR assembly for calling the COM component.
For example, to convert a Visual Basic ActiveX DLL named support.dll to a matching .NET assembly with the name NETsupport.dll, you could use this command line:
tlbimp support.dll/out: NETsupport.dll

2) Once I have developed the COM wrapper do I have to still register the COM in registry?

3) How can we use .NET components in COM (What is CCW) (COM callable wrapper)? What caution needs to be taken in order that .NET components are compatible with COM?
When a COM client calls a .NET object, the common language runtime creates the managed object and a COM callable wrapper (CCW) for the object. Unable to reference a .NET object directly, COM clients use the CCW as a proxy for the managed object.

4) How can we make Windows API calls in .NET?
Windows APIs are dynamic link libraries (DLLs) that are part of the Windows operating system. You use them to perform tasks when it is difficult to write equivalent procedures of your own. For example, Windows provides a function named FlashWindowEx that lets you make the title bar for an application alternate between light and dark shades. The advantage of using Windows APIs in your code is that they can save development time because they contain dozens of useful functions that are already written and waiting to be used. The disadvantage is that Windows APIs can be difficult to work with and unforgiving when things go wrong.

5) When we use windows API in .NET is it managed or unmanaged code?

6) What is COM?
COM is a platform-independent; object-oriented system for creating binary software components that can interact with other COM-based components in the same process space or in other processes on remote machines. COM is the foundation technology for many other Microsoft technologies, such as Active Server Pages (ASP), Automation, ISAPI, and ActiveSync.

7) What is Reference counting in COM?
The methods in the audio interfaces follow a general set of rules for counting references on the COM objects that they take as input parameters or return as output parameters.

7) Can you describe IUnknown interface in short?
The components IUnknown interface helps to maintain a reference count of the number of clients using the component. When this count drops down to zero, the component is unloaded. All components should implement the IUnknown interface. The reference count is maintained through IUnknown::AddRef() & IUnknown::Release() methods, interface discovery is handled through IUnknown::QueryInterface().
8)Can you explain what is DCOM?
Microsoft® Distributed COM (DCOM) extends the Component Object Model (COM) to support communication among objects on different computers—on a LAN, a WAN, or even the Internet. With DCOM, your application can be distributed at locations that make the most sense to your customer and to the application.
9) DTC in .NET?
The DTC is a system service that is tightly integrated with COM+. To help make distributed transactions work more seamlessly, COM+ directs the DTC on behalf of an application. This makes it possible to scale transactions from one to many computers without adding special code. The DTC proxy DLL (Msdtcprx.dll) implements the DTC interfaces. Applications call DTC interfaces to initiate, commit, abort, and inquire about transactions

10) How many types of Transactions are there in COM + .NET?

11) How do you do object pooling in .NET?

12) What are types of compatibility in VB6?

ASP.NET
1) What’s the sequence in which ASP.NET events are processed?
a) Initialize: Initialize settings needed during the lifetime of the incoming Web request.
b) Load view state: At the end of this phase, the ViewState property of a control is automatically populated
c) Process postback data: Process incoming form data and update properties accordingly.
d) Load: Perform actions common to all requests, such as setting up a database query. At this point, server controls in the tree are created and initialized, the state is restored, and form controls reflect client-side data.
e) Send postback change notifications: Raise change events in response to state changes between the current and previous postbacks.
f) Handle postback events: Handle the client-side event that caused the postback and raise appropriate events on the server.
g) Prerender: Perform any updates before the output is rendered. Any changes made to the state of the control in the prerender phase can be saved, while changes made in the rendering phase are lost.
h) Save state: The ViewState property of a control is automatically persisted to a string object after this stage. This string object is sent to the client and back as a hidden variable. For improving efficiency, a control can override the SaveViewState method to modify the ViewState property.
i) Render: Generate output to be rendered to the client.
j) Dispose: Perform any final cleanup before the control is torn down. References to expensive resources such as database connections must be released in this phase.
k) Unload: Perform any final cleanup before the control is torn down. Control authors generally perform cleanup in Dispose and do not handle this event. Initialization, Page Load, PreRendor, Page unload

2) In which event are the controls fully loaded?

3) How can we identify that the Page is PostBack?        
VB:    Public Readonly Property IsPostback as Boolean  
C#:  Public bool IsPostBack {get;}
4) How does ASP.NET maintain state in between subsequent request?
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. This is because ASP .NET maintains ViewState. The ViewState indicates the status of the page when submitted to the server. The status is defined through a hidden field placed on each page with a <form runat="server"> control. The source could look something like this:
<form name =”_ct10” method="post" action="page.aspx" id="_ctl0">             
<input type="hidden" name="__VIEWSTATE" value = “dfdsklgfgfdgfddfdl=” /></form>
Maintaining the ViewState is the default setting for ASP.NET Web Forms. If you want to NOT maintain the ViewState, include the directive  <%@ Page EnableViewState="false" %> at the top of an. aspx page or add the attribute EnableViewState="false" to any control.

5) What is event bubbling?
The ASP.NET page framework provides a technique called event bubbling that allows a child control to propagate events up its containment hierarchy. Event bubbling enables events to be raised from a more convenient location in the controls hierarchy and allows event handlers to be attached to the original control as well as to the control that exposes the bubbled event.
6) How do we assign page specific attributes?
Defines page-specific (.aspx file) attributes used by the ASP.NET page parser and compiler. Example: <%@ Page attribute="value" [attribute="value"...] %>

7) Administrator wants to make a security check that no one has tampered with ViewState, how can we ensure this?
Microsoft has provided two mechanisms for increasing the security of ViewState.
a) Machine Authentication Check (MAC) - tamper-proofing
               <%@ Page EnableViewStateMac="true"%>                                                    
b) Encrypting the ViewState This encryption can only be applied at the machine.config level, as follows: <machineKey validation='3Des' />                                                                        
8) @ Register directives?
Associates aliases with namespaces and class names for concise notation in custom server control syntax.
<%@Register tagprefix="tagprefix" Namespace="namespace" Assembly= "assembly %>
<%@ Register tagprefix="tagprefix" Tagname="tagname" Src="pathname" %>

9) What’s the use of SmartNavigation property?
Gets or sets a value indicating whether smart navigation is enabled.
VB: Public Property SmartNavigation As Boolean
C#: Public bool SmartNavigation {get; set;}

10) What is AppSetting Section in “Web.Config” file?
The <appSettings> element of a web.config file is a place to store connection strings, server names, file paths, and other miscellaneous settings needed by an application to perform work. The items inside appSettings are items that need to be configurable depending upon the environment; for instance, any database connection strings will change as you move your application from a testing and staging server into production.
 
11) Where is ViewState information stored?
The ViewState is stored in the page as a hidden form field. When the page is posted, one of the first tasks performed by page processing is to restore the view state.

12) What’s the use of @ OutputCache directive in ASP.NET?
The output cache respects the expiration and validation policies for pages
<%@ OutputCache Duration="60" VaryByParam="none"%>
Output caching is a powerful technique that increases request/response throughput by caching the content generated from dynamic pages. Output caching is enabled by default, but output from any given response is not cached unless explicit action is taken to make the response cacheable.

13) How can we create custom controls in ASP.NET?
To create a simple custom control, define a class that derives from System.Web.UI.Control and override its Render method. The Render method takes one argument of type System.Web.UI.HtmlTextWriter. The HTML that your control wants to send to the client is passed as a string argument to the Write method of HtmlTextWriter.

14) How many types of validation controls are provided by ASP.NET?
A Validation server control is used to validate the data of an input control. If the data does not pass validation, it will display an error message to the user.
The syntax:  <asp: control_name id="some_id” runat="server" />
RequiredFieldValidator: Checks that the user enters a value that falls between two values RegularExpressionValidator: Ensures that the value of an input control matches a specified pattern RequiredFieldValidator CustomValidator: Allows you to write a method to handle the validation of the value entered RangeValidator: Checks that the user enters a value that falls between two values CompareValidator: Compares the value of one input control to the value of another input control or to a fixed value ValidationSummary: Displays a report of all validation errors occurred in a Web page

15) Can you explain what is “AutoPostBack” feature in ASP.NET?
AutoPostBack automatically posted whenever the form containing textbox control Text Changed.

16) Paging in DataGrid?
The ASP.NET DataGrid control provides a built-in engine for paging through bound data. The engine supports two working modes—automatic and manual.     Automatic paging means that you bind the whole data source to the control and let it go. The control displays a proper navigation bar and handles users clicking on the movement buttons. Automatic paging doesn’t require a deep understanding of the grid’s internals, nor does it take you much time to arrange an effective solution. For large data sets, though, it might not be a smart option. Handcrafted, custom paging is the alternative. Custom paging means that the host page is responsible for filling the grid control with up-to-date information. When the grid’s current page index is, say, “3” the page must provide the set of records that fit in page number 3.
17) What’s the use of “GLOBAL.ASAX” file?
The Global.asax file, called the ASP.NET application file, provides a way to respond to application or module level events in one central location. You can use this file to implement application security, as well as other tasks. Every ASP.Net application can contain single Global.asax in its root directory. Can be use to handle application wide events and declare application wide objects.  
                                         
18) What’s the difference between “Web.config” and “Machine.Config”?
Web.config is a security in ASP.Net application and how to secure applications. Web.config does most of the work for the application the who, what, where, when and how to be authenticated Machine.config contains settings that apply to an entire computer. This file is located in the %runtime install path%\Config directory. Machine.config contains configuration settings for machine-wide assembly binding, built-in remoting channels

19) What’s a SESSION and APPLICATION object?

20) What’s difference between Server.Transfer and Response.Redirect?
Response.Redirect simply sends a message down to the browser, telling it to move to another page. So, you may run code like:  Response.Redirect ("WebForm2.aspx") Server.Transfer is similar in that it sends the user to another page with a statement such as Server.Transfer, "transfer" process can work on only those sites running on the server, you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that. Transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.

21) What’s difference between Authentication and authorization?
Authentication and Authorization are two interrelated security concepts. In short, authentication is a process of identifying a user, while authorization is the process of determining if an authenticated user has access to the resource(s) they requested.

22) What is impersonation in ASP.NET?
Impersonation is when ASP.NET executes code in the context of an authenticated and authorized client. By default, ASP.NET does not use impersonation and instead executes all code using the same user account as the ASP.NET process, which is typically the ASPNET account.
<Identity impersonate="true" UserName="domain\user" Password="password"/>
24) What are the various ways of authentication techniques in ASP.NET?  
ASP.NET provides built-in support for user authentication through several authentication providers: Forms-based authentication: the application is secured by using a custom authentication model with cookie support. Passport authentication: the application is secured by using Microsoft® Passport authentication. Passport is a single sign-on technology developed by Microsoft for use on the web. Windows authentication: the application is secured by using integrated windows authentication where access to a web application is allowed only to those users who are able to verify their windows credentials.

25) What’s difference between Datagrid, Datalist and Repeater?  From performance point of view how do they rate?
The DataGrid Web control provides the greatest feature set of the three data Web controls, with its ability to allow the end-user to sort, page, and edit its data. The DataGrid is also the simplest data Web control to get started with, as using it requires nothing more than adding a DataGrid to the Web page and writing a few lines of code. The ease of use and impressive features comes at a cost, though, namely that of performance: the DataGrid is the least efficient of the three data Web controls, especially when placed within a Web form. With its templates, the DataList provides more control over the look and feel of the displayed data than the DataGrid. Using templates, however, typically requires more development time than using the DataGrid's column types. The DataList also supports inline editing of data, but requires a bit more work to implement than the DataGrid. Unfortunately, providing paging and sorting support in the DataList is not a trivial exercise. Making up for these lacking built-in features, the DataList offers better performance over the DataGrid. Finally, the Repeater control allows for complete and total control of the rendered HTML markup. With the Repeater, the only HTML emitted are the values of the databinding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with the DataGrid and DataList. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. Furthermore, the Repeater does not offer built-in editing, sorting, or paging support. However, the Repeater does boast the best performance of the three data Web controls. Its performance is comparable to the DataList's, but noticeably better than the DataGrid's.

26) What’s the method to customize columns in DataGrid?
You can control the order, behavior, and rendering of individual columns by directly manipulating the grid's Columns collection. The standard column type -- BoundColumn -- renders the values in text labels. The grid also supports other column types that render differently. Any of the column types can be used together with the Columns collection of a DataGrid. Note that you can use explicitly-declared columns together with auto-generated columns (AutoGenerateColumns=true). When used together, the explicitly-declared columns in the Columns collection are rendered first, and then the auto-generated columns are rendered. The auto-generated columns are not added to the Columns collection.
Column Name Description BoundColumn Lets you control the order and rendering of the columns. HyperLinkColumn Presents the bound data in HyperLink controls.
ButtonColumn Bubbles a user command from within a row to an event handler on the grid. TemplateColumn Lets you control which controls are rendered in the column.
EditCommandColumn Displays Edit, Update, and Cancel links in response to changes in the DataGrid control's EditItemIndex property.

27) How can we format data inside DataGrid?
You can format items in the DataGrid Web server control to customize their appearance. You can Set the color, font, borders, and spacing for the grid as a whole. Set the color, font, and alignment for each type of grid item (row) individually, such as item, alternating item, selected item, header, and footer. Changing these settings allows you to override the settings you make for the entire grid. Set the color, font, and alignment for individual columns. This is particularly useful for setting the appearance of a special-purpose column such as a button column.
To set the format for an individual item
  1. In Design view, select the DataGrid control, then click the Property Builder link at the bottom of the Properties window.
  2. In the DataGrid Properties dialog box, click the Format tab, and under Objects do one of the following:  Select Header, Footer, or Pager. -or- Expand the Items node and select the type of item to format.
  3.  Choose font, color, and alignment options for that item, and then choose Apply.

28) How will decide the design consideration to take a Datagrid, datalist or repeater?
 
29) Difference between ASP and ASP.NET?
ASP.NET is the latest version of Microsoft's Active Server Pages technology (ASP). ASP.NET is a part of the Microsoft .NET framework, and a powerful tool for creating dynamic and interactive web pages.

30) What are major events in GLOBAL.ASAX file? What order they are triggered?
The global.asax file can be found in the root directory of an ASP.Net application. Here is the list of events you can call. By calling them you are actually overriding the event that is exposed by the HttpApplication base class.    
Application_Start: used to set up an application environment and only called when the application first starts.
Application_Init: his method occurs after _start and is used for initializing code. Application_Disposed: This method is invoked before destroying an instance of an application.     
Application_Error: This event is used to handle all unhandled exceptions in the application.            
Application_End: used to clean up variables and memory when an application ends.      Application_BeginRequest: This event is used when a client makes a request to any page in the application. It can be useful for redirecting or validating a page request.  Application_EndRequest: After a request for a page has been made, this is the last event
that is called.
Application_PreRequestHandlerExecute: This event occurs just before ASP.Net begins executing a handler such as a page or a web service. At this point, the session state is available.                       
Application_PostRequestHandlerExecute: This event occurs when the ASP.Net handler finishes execution.
Application_PreSendRequestHeaders: This event occurs just before ASP.Net sends HTTP Headers to the client. This can be useful if you want to modify a header. Application_PreSendRequestContent: This event occurs just before ASP.Net sends content to the client.
Application_AcquireRequestState: This event occurs when ASP.Net acquires the current state (eg: Session state) associated with the current request.
Application_ReleaseRequestState: This event occurs after ASP.NET finishes executing all request handlers and causes state modules to save the current state data.                         Application_AuthenticateRequest: This event occurs when the identity of the current user has been established as valid by the security module.
Application_AuthorizeRequest: This event occurs when the user has been authorized to access the resources of the security module.
Session_Start: this event is triggered when any new user accesses the web site.
Session_End: this event is triggered when a user's session times out or ends. Note this can be 20 mins (the default session timeout value) after the user actually leaves the site.


19) Can we force garbage collector to run?
It is also possible to force the garbage collector to perform a collection by calling one of the two methods shown here:
void GC.Collect(Int32 Generation)
void GC.Collect()

For more detail
2.   Which data type among these does RangeValidator doesn’t support?
Integer, char, string, Boolean, date - Boolean
3.   SQL 2000,sql server 7.0 + - all SQL database – Which namespace??? SQL Client
4.   do we Allow Query String along with [Server.Transfer] & [Server.Execute] ?
5.   which Interface for Giving unique Ids :- iAppDomainSetup,iCustomFormatter,iNamingContainer ?
6.   Whats the primary/main Difference b/w Abstract Class & Interface ? [w.r.t. Implementation point]
7.   full-form of W S D L ? - Web Service Description Language
8.   ASP.NET Best-Feature platform independent OR provides best web-based stuff for Win 2K onwards???
9. .aspx Page – Single Scripting Langg. OR Multiple?  - Multiple e.g. HTML, XML, JavaScript, VB..
10.Viewstate – if we have a Class, its Instance, Can I view the state of that instance???
11.What r the OOPs features used in ASP.NET?
 Inheritance,Polymorphism & Abstraction, Encapsulation.
12.How many forms [.aspx WebForms] u can use/allow in ASP.NET?  - Many
12.   Clone [vb.net object] ; Does it create a Shallow copy or Deep copy ?? – creates Shallow copy !
13.   Databinding is relating Set of Controls to Dataset table-columns directly !!!
14.   Wats Ad Hoc querying ???
It simply means AAA querying => Anywhere, Anytime Anyhow sql-querying !!!!!!!
15.   XML-document Class – create/return an xml node objt ::::
Create < node ; Attribute ; Element > ; which one ????
17.  In the Contexts of {Winform - an inherited form} & ‘ w.r.t WinForm & individual Controls ….
' {Tool from toolbox};is there a Difference in the Event Handling
' in the 2 cases OR not ...Explain with reason ?
‘ Does the Event Handling differ in each case? Or theres no ‘‘ difference ?

Q:SQL – Trasaction – Saving :- SQL save-changes [rite way] :-
Is It
Commit OR
Command-Commit OR
Connection-Commit ?
Q:For sql parametrized Stored Procedure ---
sqlcommand,sqlparam,sqlconnection,All of 'em ?
Q: Multiple Inheritance ??? Can there be 2 [ sub main() ] in 1 Pjct/Application ?
No, Multiple Inheritance NOT supported in .NET
YES, 2 Mains [ main() ] perfectly possible in a Single .EXE; only issue is U need to specify which main() is the Startup object ?!
29. GET & POST methods in <html> ???
Adv. of Post over Get ?
31. Diff. b/w COM & DCOM ?
35. Wat r 2 types of Submit w.r.t SUBMIT-action in ASP.NET ?

1. What r the different types of Indexes ?
Microsoft SQL Server supports two types of indexes:
Clustered indexes define the physical sorting of a database table’s rows in the storage media. For this reason, each database table may have only one clustered index. If a PRIMARY KEY constraint is created for a database table and no clustered index currently exists for that table, SQL Server automatically creates a clustered index on the primary key.
Non-clustered indexes are created outside of the database table and contain a sorted list of references to the table itself. SQL Server 2000 supports a maximum of 249 non-clustered indexes per table. However, it’s important to keep in mind that non-clustered indexes slow down the data modification and insertion process, so indexes should be kept to a minimum
2. Can a SQL Trigger be automatically activated ?
I really dont understand the meaning of this question.to be specific all the triggers are activated automatically when a record is inserted, updated, deleted .
3. Advantages and disadvantages of indexes
Although the optimizer decides whether to use an index to access table data, except in the following case, you must decide which indexes might improve performance and create these indexes. Exceptions are the dimension block indexes and the composite block index that are created automatically for each dimension that you specify when you create a multi-dimensional clustering (MDC) table.
You must also execute the RUNSTATS utility to collect new statistics about the indexes in the following circumstances:
After you create an index
After you change the prefetch size
You should also execute the RUNSTATS utility at regular intervals to keep the statistics current. Without up-to-date statistics about indexes, the optimizer cannot determine the best data-access plan for queries.

Note:
To determine whether an index is used in a specific package, use the SQL Explain facility. To plan indexes, use the Design Advisor from the Control Center or the db2advis tool to get advice about indexes that might be used by one or more SQL statements.
4. Advantages of an index over no index ?
If no index exists on a table, a table scan must be performed for each table referenced in a database query. The larger the table, the longer a table scan takes because a table scan requires each table row to be accessed sequentially. Although a table scan might be more efficient for a complex query that requires most of the rows in a table, for a query that returns only some table rows an index scan can access table rows more efficiently.

The optimizer chooses an index scan if the index columns are referenced in the SELECT statement and if the optimizer estimates that an index scan will be faster than a table scan. Index files generally are smaller and require less time to read than an entire table, particularly as tables grow larger. In addition, the entire index may not need to be scanned. The predicates that are applied to the index reduce the number of rows to be read from the data pages.

7 If an ordering requirement on the output can be 7 matched with an index column, then scanning the index in column order will 7 allow the rows to be retrieved in the correct order without a sort.

Each index entry contains a search-key value and a pointer to the row containing that value. If you specify the ALLOW REVERSE SCANS parameter in the CREATE INDEX statement, the values can be searched in both ascending and descending order. It is therefore possible to bracket the search, given the right predicate. An index can also be used to obtain rows in an ordered sequence, eliminating the need for the database manager to sort the rows after they are read from the table.

In addition to the search-key value and row pointer, an index can contain include columns, which are non-indexed columns in the indexed row. Such columns might make it possible for the optimizer to get required information only from the index, without accessing the table itself.

Note:
The existence of an index on the table being queried does not guarantee an ordered result set. Only an ORDER BY clause ensures the order of a result set.
Although indexes can reduce access time significantly, they can also have adverse effects on performance. Before you create indexes, consider the effects of multiple indexes on disk space and processing time:

Each index requires storage or disk space. The exact amount depends on the size of the table and the size and number of columns in the index.
Each INSERT or DELETE operation performed on a table requires additional updating of each index on that table. This is also true for each UPDATE operation that changes the value of an index key.
The LOAD utility rebuilds or appends to any existing indexes.
The indexfreespace MODIFIED BY parameter can be specified on the LOAD command to override the index PCTFREE used when the index was created.

Each index potentially adds an alternative access path for a query for the optimizer to consider, which increases the compilation time.
Choose indexes carefully to address the needs of the application program.

Whats the root Base Class in an ASP.NET Web Application ?
System.Web.UI.Page

Differemce between triggers and Storedprocedures?
Triggers are basically used to implement business rules. Triggers is also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database. Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table
CAS: Code Access Security
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.
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.).
Uses of Singleton Activation Mode:
singleton Activation mode used for, the server object is instantiated for responding number of clients .
singlecall Activation mode used for the Server Object is instantiated for responding to just one single request







Garbage Collection in .NET - How it really works
Garbage collection is a process of releasing the memory used by the objects, which are no longer referenced. This is done in different ways and different manners in various platforms and languages. We will see how garbage collection is being done in .NET.


Garbage Collection basis


Almost every program uses resources such as database connection, file system objects etc. In order to make use of these things some resources should be available to us.
First we allocate a block of memory in the managed memory by using the new keyword.
Use the constructor of the class to set the initial state of the object.
Use the resources by accessing the type's members
At last CLEAR THE MEMORY
But how many times have programmers forgotten to release the memory. Or how many times the programmers try to access the memory which was cleaned.


These two are the serious bugs, which will lead us to memory leak and commonly occurring. In order to overcome these things the concept of automatic memory management has come. Automatic memory management or Automatic garbage collection is a process by which the system will automatically take care of the memory used by unwanted objects (we call them as garbage) to be released. Hurrah... Thanks to Microsoft's Automatic Garbage collection mechanism.


Automatic Garbage Collection in .NET


When Microsoft planned to go for a new generation platform called .NET with the new generation language called C#, their first intention is to make a language which is developer friendly to learn and use it with having rich set of APIs to support end users as well. So they put a great thought in Garbage Collection and come out with this model of automatic garbage collection in .NET.


They implemented garbage collector as a separate thread. This thread will be running always at the back end. Some of us may think, running a separate thread will make extra overhead. Yes. It is right. That is why the garbage collector thread is given the lowest priority. But when system finds there is no space in the managed heap (managed heap is nothing but a bunch of memory allocated for the program at run time), then garbage collector thread will be given REALTIME priority (REALTIME priority is the highest priority in Windows) and collect all the un wanted objects.


How does Garbage collector locate garbage


When an program is loaded in the memory there will be a bunch of memory allocated for that particular program alone and loaded with the memory. This bunch of memory is called Managed Heap in .NET world. This amount of memory will only be used when an object is to be loaded in to the memory for that particular program.


This memory is separated in to three parts :


Generation Zero
Generation One
Generation Two
Ideally Generation zero will be in smaller size, Generation one will be in medium size and Generation two will be larger.


When we try to create an object by using NEW keyword the system will,


Calculate the number of bytes required for the object or type to be loaded in to the managed heap.
The CLR then checks that the bytes required to allocate the object are available in the reserved region (committing storage if necessary). IF the object fits, it is allocated at the address pointed to by NextObjPtr.
These processes will happen at the Generation zero level.
When Generation Zero is full and it does not have enough space to occupy other objects but still the program wants to allocate some more memory for some other objects, then the garbage collector will be given the REALTIME priority and will come in to picture.


Now the garbage collector will come and check all the objects in the Generation Zero level. If an object's scope and lifetime goes off then the system will automatically mark it for garbage collection.


Note:


Here in the process the object is just marked and not collected. Garbage collector will only collect the object and free the memory.


Garbage collector will come and start examining all the objects in the level Generation Zero right from the beginning. If it finds any object marked for garbage collection, it will simply remove those objects from the memory.


Here comes the important part. Now let us refer the figure below. There are three objects in the managed heap. If A and C are not marked but B has lost it scope and lifetime. So B should be marked for garbage collection. So object B will be collected and the managed heap will look like this.


But do remember that the system will come and allocate the new objects only at the last. It does not see in between. So it is the job of garbage collector to compact the memory structure after collecting the objects. It does that also. So the memory would be looking like as shown below now.
But garbage collector does not come to end after doing this. It will look which are all the objects survive after the sweep (collection). Those objects will be moved to Generation One and now the Generation Zero is empty for filling new objects.


If Generation One does not have space for objects from Generation Zero, then the process happened in Generation Zero will happen in Generation one as well. This is the same case with Generation Two also.


You may have a doubt, all the generations are filled with the referred objects and still system or our program wants to allocate some objects, then what will happen? If so, then the MemoryOutofRangeException will be thrown.


Dispose


Instead of declaring a Finalizer, exposing a Dispose method is considered as good.








Public void Dispose()


{


// all clean up source code here..


GC.SuppressFinalize(this);


}If we clean up a object, using Dispose or Close method, we should indicate to the runtime that the object is no longer needed finalization, by calling GC.SuppressFinalize() as shown above.


If we are creating and using objects that have Dispose or Close methods, we should call these methods when we’ve finished using these objects. It is advisable to place these calls in a finally clause, which guarantees that the objects are properly handled even if an exception is thrown.




Serialization is the process of saving the state of an object by converting it to a stream of bytes. The object can then be persisted to file, database, or even memory. The reverse process of serialization is known as deserialization (see Figure A). In this article, I discuss the uses of serialization and various techniques that can be used to perform serialization. I also take a look at how serialization works and how I can selectively prevent certain members of an object from being serialized.




















Uses for serialization
Serialization is used in many scenarios, but the main purpose is to save the state of an object in order to have the ability to recreate the same object when required. It is an important to let the user save work and then be able to continue from that point at a later time. This is a common need in various tools and applications. Serialization is also used in creating a clone of an object.


Another important need for serialization arises when the object is required to travel electronically over wire. In such cases the objects are serialized and deserialized. In fact, serialization is one of the fundamental requirements for techniques such as .NET Remoting.


Even the hibernation mode in the Windows Operating system can be considered a form of serialization.


Types of serialization
The .NET Framework provides certain built-in mechanisms which can be used to serialize and deserialize objects. This functionality can be found in the System.Runtime.Serialization and the System.Xml.Serialization namespaces of the .NET Framework.


Serialization in .NET can be classified into four types as shown in Figure B:




Figure B








Four types






This classification arises from the format in which the data in the object is persisted. Each of the serialization techniques mentioned have different capabilities and each excel in specific scenarios. The XML serialization technique can convert only the public properties and fields of an object into an XML format. The XML serialization is also known as shallow serialization.


This inability of the XMLSerializer to serialize the private fields of an object is overcome by the SOAP and binary serialization techniques. In the binary and SOAP serialization techniques, the state of the entire object is serialized into a stream of bytes. In cases where the object contains a reference to other objects, even those are serialized. This type of serialization is known as deep serialization.


In addition to these techniques, the .NET Framework also provides the developer control over the serialization process. This can be achieved by implementing the ISerializable interface, which will be discussed separately under custom serialization in the next part of this article.












The SOAP and binary serialization functionality is provided by means of various Formatters in the .NET Framework. Aligned with the classifications of XML serialization and binary serialization, the .NET Framework also provides the SoapFormatter and the BinaryFormatter classes. These classes implement the IRemotingFormatter and the IFormatter interfaces.


The main methods which encapsulate the functionality of serialization are the Serialize and Deserialize methods. The SoapFormatter and the BinaryFormatter are the concrete classes which enable the serialization process within the .NET Framework.


Let us now take a look at some code. The code in Listing A shows a sample class being serialized and deserialized in C#.


An instance of the SoapFormatter object is created and the Serialize method is called and a FileStream is passed to enable serialization. The technique for using a binary formatter would be the same except that instead of the SoapFormatter, an instance of the BinaryFormatter would need to be created.


Comparison: Which technique to use?
The XmlSerializer can be used when you need the data in the object to be stored in an XML Format. However, this serialize has the limitation that it can serialize only the public fields of an object.


The SoapFormatter is ideal in scenarios where you need interoperability. This is ideal in applications spanning heterogeneous environments.


The BinaryFormatter generates a very compact stream when an object is serialized as compared to the other two techniques and hence is useful when data needs to travel electronically across the wire. This is appropriate when the applications do not involve heterogeneous environments.


Serializable attribute
The developer would need to mark a class as serializable using the appropriate attribute in order for the object of that class to indeed be serializable. In fact, the serialization feature is a design time issue because an object cannot be made serializable at runtime.


The code snippet below shows the usage of SerializableAttribute:
[Serializable]
public class MyClass


The SerializableAttribute needs to be applied even when the class implements the ISerializable interface. When an attempt is made to serialize an object which is not marked as Serializable, the CLR throws a SerializationException.


The SerializableAttribute comes in handy whenever the object needs to cross application domains or travel over the wire. The developer does not need to write any plumbing code for the serialization process to work. Once a class is marked as serializable, if the need arises for serialization, the .NET Framework will employ reflection and automatically serialize and deserialize objects which cross application domains or participate in .NET Remoting.


Selective serialization
In certain scenarios, it may be beneficial to serialize an object in parts. Certain objects might contain information which is sensitive and for security reasons such information should not be serialized. Also, it might not make sense to serialize certain data like the reference to another object or storing a Thread ID. This data might not be valid when the object is deserialized.


For such situations, the .NET Framework provides the NonSerialized attribute. This attribute can be used to prevent particular member variables of an object from being serialized.


The sample code in Listing B demonstrates this attribute.


In the sample code listing, if the SampleObject class were to be serialized, then the data in string variable strSecret would not.


This attribute however, does not apply to the XMLSerializer. The same results could be obtained using the XMLSerializer by making use of the XmlIgnoreAttribute class.


The code sample in Listing C shows how the same results could be obtained using XMLSerializer.


Serialization
In this introductory article to serialization I looked at what serialization is and where it is used. The article also dealt with selective serialization where only parts of an object are to be serialized. The final part of this article deals with more advanced topics associated with serialization such as implementing ISerializable and ICloneable.






Ajax Postback




It is necessary to know if user just opened our ASP.NET page for the first time, or he has pressed some submit controls and caused page Postback to send information or commands to the server.


Before Ajax came along there was only one type of Postback - a regular, full Postback of the page to the server, where all the information from the form was sent to the server, and completely new ASP.NET page was generated and its HTML code was returned to the users web browser to render it and completely replace the old page.


With Ajax we now have a Partial (Asynchronous) Postback, where specific information or command is sent to the server, where only a necessary part of the page is re-generated and returned to the user, and this new part of the page is inserted dynamically into the previous page contents, without a full reload of the page.


This is off course a major advantage of the new Ajax model over the old approach.


Since there are now two types of Postbacks we really need to know what type of Postback occurred on our page.


Here is how to determine this: We can retrieve the instance of the ScriptManager class of the current Page via static GetCurrent method and inspect its IsInAsyncPostBack property to determine if Partial (Asynchronous) Postback has occurred:


Here is the example code:








protected void Page_Load(object sender, EventArgs e)


{


if (Page.IsPostBack)


{


// get a reference to ScriptManager and check if we have a partial postback


if (ScriptManager.GetCurrent(this.Page).IsInAsyncPostBack)


{


// partial (asynchronous) postback occured


// insert Ajax custom logic here


}


else


{


// regular full page postback occured


// custom logic accordingly


}


}


}




Based on this information we can determine the type of the Postback that has occurred on the page and apply our custom page logic accordingly.












STATE MANAGEMENT
State can be managed in two ways
Client-Side :
Query Strings,View State Property, Hidden Fields, Cookies
Server-Side :
Application state, Session state, Database Support


Request.Querystring :
Request.Querystring is client side state management. The querystring value will be visible to the end users through browser address bar.Using GET method we can post form datas to the next form and get the data using request.querystring.The values are visible in the address bar in the browser.if you moving the next form the previous values are lost.


Request.querystring will retain the value to the next page only assigning values to url:
Example:
Response.Redirect ("webform.aspx?=name="+test));


Advantages of Query String:
A query string is contained in the HTTP request for a specific URL.so, no server resource is required to process it.


Disadvantages:
values are not visible in the addressbar.
if you moving the next form the previous values are lost.




ViewState :
When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. This is because of ViewState.Sessions are maintained at application level where as ViewState is maintained at PageLevel/WebControl.This View State is used to maintain State of a WebControls after form submission.The status is defined through a hidden field placed on each page with a


control.We can disable this Property by Making Enable ViewState Property as False.


Advantages:
Form reappears in the browser window together with all form values after submission.
Easy to Maintain


Disadvantages:
Load increases to storage of Values
As the no of values increases Performance decreases


Hidden Fields:
A hidden field is an Html control.They are not displayed in the browser but its value will be maintained.A hidden field is used to pass along variables/values from one form to another page without forcing the user to re-enter the information
syntax:


id or name attribute is used to specify a name of a hidden field


Advantages:
Simple and light weight
Performance is more


Disadvantages:
Cannot store large Values


Cookies:
A cookie is a name value Pair.Without cookies, each retrieval of a Web page or component of a Web page is an isolated event
it is information for future use that is stored by the server on the client side of a client/server.Security is less becoz cookies can easily tampered.A cookie is a mechanism that allows the server to store its own information about a user on the user's own computer


advantages:
Light weight
Less complexicity


Disadvantages:
cant use for more data
Information can be Tampered.
As the number of Cookies increases Performance decreases


Sessions:
In Asp.net sessions plays a prominent role because it is used to store specific session of a user.Unlike request.Querystring
values are invisible to the user thus providing security.If different users are accessing a Web application, each will have a different session state.If user logins for a particular application A unique 120-bit SessionID string containing ASCII character will bw created.The session data is stored on web server.
Session Events like Session_Start,Session_End can be handeled in a file called Global.asax.A default timeout is 20. we change according to our requirement by changing the timeout property in Web.config file


mode="InProc"
timeout="20"
/>




Since the session data is stored on the Web server, if the server crashes the session data would be lost. so, you can store session data in a separate service.The default location is in the ASP.Net process. Sessions can be stored in 3 ways.
1.)InProcess
When the Web Server is used to store the session state data, the process mode is InProc ( in-process)
2.)OutProcess
when session state data is stored on any state machine , the process mode is OutProcess
3.)SqlServer
we can strore session state out of process by storing data in a Microsoft SQL Server database. The advantage is that you can cluster multiple database servers so that if one fails, another can take over the state management.


By default session state is enabled for all pages of your application.




Session can be killed by using Session.Abandon method.Session variables can be added or removed by using Remove and Add methods.


Advantages:
Session state information is not visible to the user.
Session will be maintained through out the application for a specific user untill his/her session Expires or user explicitly
logsout


Disadvantages:
Session state variables are stored in memory until they are either removed or replaced resulting in degrading Web server performance.
Whenever you stop the Web Server or restart IIS you will lose all of your session state information.
since they are stored on the server we must go to the server to get the information which is slower than if it was stored on the client side.
Since it is stored outside of the web server and the client, then you don't lose information if either of web machine fails. To use session state on the SQL server alter your web.config file:








Application State:
Application state is created when each browser request is made for a specific URL. After an application state is created, the application-specific information is stored in it. All information stored in the application state is shared among all the pages of the Web application . Variables and objects added to the application state are global to an ASP.NET application.


If an object is added to an application state, it remains in the application state until the application is shut down, the Global.asax file is modified, or the item is explicitly removed from the application state.
Syntax :


Application["appVar"] = "Ravi";




To remove the application variable appVar from the application state, we need to write
Application.Remove(["appVar"]);
If we want to remove all variable for application state we need to write
Application.RemoveAll();




Since these variables are global to an application, we need to consider the following issues while storing any value in an application state variable:


The memory occupied by variables stored in an application state is not released until the value is either removed or replaced. Therefore, the number of variables and objects in an application state should be minimum. Otherwise, it will be an overhead on the Web server and the server response will be slow.


Multiple pages within an application can access values stored in an application state simultaneously. Therefore, explicit synchronization methods need to be used to avoid deadlocks and access violations.


Multiple pages within an ASP.NET Web application can simultaneously access values, stored in an application state. This can result in conflicts and deadlocks.To avoid such situations, the HttpApplicationState class provides two methods, LOCK ( ) and UNLOCK ( ). These methods only allow one thread at a time to access applications state variables and objects.


Calling the Lock ( ) method on an Application object causes ASP.NET to block attempts by the code running on other worker threads to access anything in an application state. These threads are unblocked only when the thread that called the Lock ( ) method calls the corresponding Unlock ( ) method on the Application object.
Example:
Create a new ASP.NET Web application.
Add the following lines of code in the Page_Load event of the page:


Application.Lock();
if(Application["PageCounter"]==null)
Application[ "PageCounter" ]=0;
Application[ "PageCounter" ]=(int)Application[ "PageCounter" ]+1;
Response.Write (Application[ "PageCounter" ]);
Application.UnLock ();


Advantages :
Application state is easy to use and is consistent with other .NET Framework classes.
Storing information in application state involves maintaining only a single copy of information.


Disadvantages:
The data stored in an application state is lost when the Web server containing the application state fails due to a server crash, upgrade, or shutdown. Application state requires server memory and can affect the performance of the server and the scalability of the Web application.






Page Level Output Caching


This is at the page level and one of the easiest means for caching pages. This requires one to specify Duration of cache and Attribute of caching.


Syntax: Duration="60" VaryByParam="none" %


The above syntax specifies that the page be cached for duration of 60 seconds and the value "none" for VaryByParam* attribute makes sure that there is a single cached page available for this duration specified.


* VaryByParam can take various "key" parameter names in query string. Also there are other attributes like VaryByHeader, VaryByCustom etc. Please refer to MSDN for more on this.


2. Fragment Caching


Even though this definition refers to caching portion/s of page, it is actually caching a user control that can be used in a base web form page. In theory, if you have used include files in the traditional ASP model then this caching model is like caching these include files separately. In ASP.NET more often this is done through User Controls. Initially even though one feels a bit misleading, this is a significant technique that can be used especially when implementing "n" instances of the controls in various *.aspx pages. We can use the same syntax that we declared for the page level caching as shown above, but the power of fragment caching comes from the attribute "VaryByControl". Using this attribute one can cache a user control based on the properties exposed.


Syntax: <%@ OutputCache Duration="60" VaryByControl="DepartmentId" % The above syntax when declared within an *.ascx file ensures that the control is cached for 60 seconds and the number of representations of cached control is dependant on the property "DepartmentId" declared in the control. Cache Dependency on SQL One of the biggest improvements in ASP.NET 2.0 Caching is the feature of Cache dependency on database tables. This means that the data will be present in the Cache as long as the table entries does not change. As, soon as the database table is changed the Cache is expired. You can enable the SQL Cache dependency by using the aspnet_regsql.exe command line tool. Simply, type the following command on the Visual Studio.NET 2005 command line. Collapse Copy Code aspnet_regsql -ed -E -d SchoolThe command above will enable the Cache dependency on the "School" database. The next step is to enable the caching on the individual table. You can do that by using the following line. Collapse Copy Code aspnet_regsql -et -E -d School -t UsersThe above line will enable the caching on the Users table which is contained in the School database. The next step is to create the connectionString in the connectionStrings section and sqlCacheDependency in the web.config file. Take a look at the code below: Collapse Copy Code connectionString="Server=localhost;Database=School;Trusted_Connection=true"/> lt;/caching>As, you have noticed that the sqlCacheDependency have a pollTime attribute which is set to "1000" milliseconds. This means that the ASP.NET will check the database table for any changes every 10 seconds. The database section of the contains the connectionString which is used to connect to the database.


The final step is to use the caching in your code. You can do this in various ways. Take a look at the following code which uses caching programmatically.


Collapse Copy Code


private void BindData(){ // if null then fetch from the database if (Cache["Users"] == null) { // Create the cache dependency SqlCacheDependency dep = new SqlCacheDependency("School", "Users"); string connectionString = ConfigurationManager.ConnectionStrings[ "ConnectionString"].ConnectionString; SqlConnection myConnection = new SqlConnection(connectionString); SqlDataAdapter ad = new SqlDataAdapter("SELECT FirstName, LastName " + "FROM Users", myConnection); DataSet ds = new DataSet(); ad.Fill(ds); // put in the cache object Cache.Insert("Users", ds, dep); } gvUsers.DataSource = Cache["Users"] as DataSet; gvUsers.DataBind();}The line SqlCacheDependency dep = new SqlCacheDependency("School", "Users"); is used to create the caching on the School database and Users table. In the beginning of the BindData method I check that if the item is already in the Cache. If it is then I simply return the item using caller by casting it from the Cache object. If the item is not in the Cache then the data is fetched from the database and inserted into the Cache object. The Cache will be discarded anytime you make a change in the database table "Users". This means that if you INSERT, DELETE, UPDATE any data in any row in the Users table then the Cache will be considered obsolete and a copy of the fresh data will be fetched from the database.


Caching in SQL Server 2005 have a different architecture then in SQL Server 2000. You don't have to write any lines in web.config to enable Caching in SQL Server 2005. Also, in SQL Server 2005 the Cache is only expired when the row is changed in the database table.






Data Contracts
Message Contracts


Data Contracts primarily target the XSD schema definitions of Soap Messages
Message Contracts primarily target the and construction


Data Contracts can control only the contents of Soap message data. Just the types between the section
Message Contracts can control the whole SOAP message


Data Contracts are mostly used while dealing with serialized types within the message body
Message Contracts are mostly used while passing security information as tokens, correlation guids into the soap headers


Data contracts take care of the Data Structures of the message e.g. defining complex types, collections, etc
Message Contracts take care of the overall message structure of the WSDL




Data Contract Serialization


· You can apply the DataMemberAttribute attribute to fields, and properties.


· Member accessibility levels (internal, private, protected, or public) do not affect the data contract in any way.


· The DataMemberAttribute attribute is ignored if it is applied to static members.


· During serialization, property-get code is called for property data members to get the value of the properties to be serialized.


· During deserialization, an uninitialized object is first created, without calling any constructors on the type. Then all data members are deserialized.


· During deserialization, property-set code is called for property data members to set the properties to the value being deserialized.




Types of Parameters in C#
Parameters are means of passing values to a method.The syntax of passing parameter in C# is


[modifiers] DataType ParameterName


There are four different ways of passing parameters to a method in C#.The four different types of parameters are


1. Value2. Out3. Ref4. Params1.Value parameters This is the default parameter type in C#.If the parameter does not have any modifier it is “value” parameter by default.When we use “value” parameters the actual value is passed to the function,which means changes made to the parameter is local to the function and is not passed back to the calling part.


using System;class ParameterTest{ static void Mymethod(int Param1) { Param1=100; } static void Main() { int Myvalue=5; MyMethod(Myvalue); Console.WriteLine(Myvalue); }}Output of the above program would be 5.Eventhough the value of the parameter Param1 is changed within MyMethod it is not passed back to the calling part since value parameters are input only.2.Out parameters “out” parameters are output only parameters meaning they can only passback a value from a function.We create a “out” parameter by preceding the parameter data type with the out modifier. When ever a “out” parameter is passed only an unassigned reference is passed to the function.


using System;class ParameterTest{ static void Mymethod(out int Param1) { Param1=100; } static void Main() { int Myvalue=5; MyMethod(Myvalue); Console.WriteLine(out Myvalue); }}Output of the above program would be 100 since the value of the “out” parameter is passed back to the calling part. NoteThe modifier “out” should precede the parameter being passed even in the calling part. “out” parameters cannot be used within the function before assigning a value to it. A value should be assigned to the “out” parameter before the method returns.


3.Ref parameters “ref” parameters are input/output parameters meaning they can be used for passing a value to a function as well as to get back a value from a function.We create a “ref” parameter by preceding the parameter data type with the ref modifier. When ever a “ref” parameter is passed a reference is passed to the function.


using System;class ParameterTest{ static void Mymethod(ref int Param1) { Param1=Param1 + 100; } static void Main() { int Myvalue=5; MyMethod(Myvalue); Console.WriteLine(ref Myvalue); }}Output of the above program would be 105 since the “ref” parameter acts as both input and output.Note


The modifier “ref” should precede the parameter being passed even in the calling part. “ref” parameters should be assigned a value before using it to call a method


. 4.Params parameters “params” parameters is a very useful feature in C#. “params” parameter are used when a variable number of arguments need to be passed.The “params” should be a single dimensional or a jagged array.


using System;class ParameterTest{ static int Sum(params int[] Param1) { int val=0; foreach(int P in Param1) { val=val+P; } return val; } static void Main() { Console.WriteLine(Sum(1,2,3)); Console.WriteLine(Sum(1,2,3,4,5)); }}Output of the above program would be 6 and 15.Note


The value passed for a “params” parameter can be either comma separated value list or a single dimensional array. “params” parameters are input only.


































There are couple of advantage of LINQ over stored procedures.


1. Debugging - It is really very hard to debug the Stored procedure but as LINQ is part of .NET, you can use visual studio's debugger to debug the queries.


2. Deployment - With stored procedures, we need to provide an additional script for stored procedures but with LINQ everything gets complied into single DLL hence deployment becomes easy.


3. Type Safety - LINQ is type safe, so queries errors are type checked at compile time. It is really good to encounter an error when compiling rather than runtime exception!














Side-by-side execution is the ability to run multiple versions of an application or component on the same computer. You can have multiple versions of the common language runtime, and multiple versions of applications and components that use a version of the runtime, on the same computer at the same time.


















































Difference between Arraylist and Generic List




private void button1_Click
(object sender, EventArgs e)
{
//Arraylist - Arraylist accept values as object
//So i can give any type of data in to that.
//Here in this eg: an arraylist object accepting
//values like String,int,decimal, char and a custom object


Employee emp = new Employee("2", "Litson");
ArrayList arr = new ArrayList();
arr.Add("Sabu");
arr.Add(234);
arr.Add(45.236);
arr.Add(emp);
arr.Add('s');
//This process is known as boxing


//To get inserted vales from arraylist we have to specify the index.
//So it will return that values as object.
//we have to cast that value from object to its original type.


String name = (String)arr[0];
int num = (int)arr[1];
decimal dec = (decimal)arr[2];
Employee em = (Employee)arr[3];
char c = (char)arr[4];
//This process that is converting from object to its original type is known as unboxing
//------------------------------------------------------------------------------------
//Generic List
//List<>


//Main advantage of Generic List is we can specify the type of data we are going to insert in to
//List. So that we can avoid boxing and unboxing
//Eg:
List strLst = new List();
strLst.Add("Sabu");//Here List accepting values as String only
strLst.Add("Litson");
strLst.Add("Sabu");
strLst.Add("Sabu");


List intLst = new List();
intLst.Add(12);//Here List accepting values as int only
intLst.Add(14);
intLst.Add(89);
intLst.Add(34);


List decLst = new List();
decLst.Add(2.5M);//Here List accepting values as deciaml only
decLst.Add(14.4587m);
decLst.Add(89.258m);
decLst.Add(34.159m);


List empLst = new List();
empLst.Add(new Employee("1", "Sabu"));//Here List accepting Employee Objects only
empLst.Add(new Employee("2", "Mahesh"));
empLst.Add(new Employee("3", "Sajith"));
empLst.Add(new Employee("4", "Binu"));




//To get values from Generic List
String nme = strLst[0]; //No need of casting
int nm = intLst[0];
Decimal decVal = decLst[0];
Employee empVal = empLst[0];






























































The control state
All controls in ASP.NET inherit the View State property from the Control Class. The state is stored in Name/value pairs and the view state property returns an instance of the StateBag class which is a specialized dictionary object. At a level of abstraction the Control state and the View state are similar but have several differences in handling.




View State


Control State


View state is a property inherited from the control class and is inherited by all controls. It is independent of the Control’s state.


Control state is the control’s private view state. Control state is designed for storing a control's essential data (such as the page number of a pager control) that must be available on postback when view state is disabled.


View state can be enabled or disabled for an entire page or for a specific control


Control state cannot be disabled for a control.


View state is sent by the server as a hidden variable in a form, as part of every response to the client, and is returned to the server by the client as part of a postback. However, to reduce bandwidth demand when using mobile controls, ASP.NET does not send a page's view state to the client. Instead, the view state is saved as part of a user's session on the server. Where there is a view state, a hidden field that identifies this page's view state is sent by the server as part of every response to the client, and is returned to the server by the client as part of the next request. However, since the view state for a given page must be kept on the server, it is possible for the current state to be out of synchronization with the current page of the browser, if the user uses the Back feature on the browser to go back in the history.


The control state is stored in the same hidden variable as the view state. Even when view state is disabled control state travels to the client and back to the server in the page. On postback the hidden variable is deserialized and the control state is loaded into each control that is registered for the control state mechanism.
































is


The is operator is used to check whether the run-time type of an object is compatible with a given type. The is operator is used in an expression of the form:


The is operator cannot be overloaded.


Note that the is operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered by the is operator.


as


The as operator is used to perform conversions between compatible types. The as operator is used in an expression of the form:


Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed using cast expressions.




JavaScript Form Submit Example
The code:


id="myform" action="submit-form.php">Search: type='text' name='query'> href="javascript: submitform()">Submit
When to use MARS


Mars should be used in two core scenarios,
1) When using MARS results in cleaner looking code
2) When using Transactions and there is a need to execute in the same isolation level scope
Mars comes with a cost in fact there are a lot of hidden costs associated with this feature, costs in the client, in the network layer and in the server. On the client we run into an issue where creating a new batch is not free, we kind of work around this issue by pooling mars commands but it is still expensive if you don’t used the pooled functionality. On the network layer there is a cost associated with multiplexing the TDS buffer, opening too many batches can be more expensive than opening another connection. On the server all MARS batches run in the same scope, worst case scenario your queries will end up running in the order received.
MARS feature can be enables or disabled by the connection string keyword “MultipleActiveResultSets”.This property can be set to true or false depending on whether you want MARS or not.






SqlConnection con = new SqlConnection(“Here goes your ConnectionString“);


SqlDataReader reader;


SqlCommand cmd = new SqlCommand(”Select * From tableName where pk = WhateverField”, con);


if(con.State != ConnectionState.Open){con.Open();}


reader = cmd.ExecuteReader


Co-related query


USE AdventureWorks;


GO


SELECT e.EmployeeID


FROM HumanResources.Employee e


WHERE e.ContactID IN


(


SELECT c.ContactID


FROM Person.Contact c


WHERE MONTH(c.ModifiedDate) = MONTH(e.ModifiedDate)


)


GO


























Encapsulation:-


Interview Definition:- Binding data and member functions together inside a single unit.
How to Encapsulate:- By creating types e.g Classes and Struct
Bu using encapsulation we can create out own custom types by reusing the existing or primitive types.


Abstraction:-


Abstraction defines way to abstract or hide your data and members from outside world. Simply speaking Abstraction is hiding the complexities of your class or struct or in a generic term Type from outer world. This is achieved by means of access specifiers.
Interview Definition: - Hiding the complexities of your type from outside world.
How to Abstract: - By using Access Specifiers
.Net has five access specifiers:-
Public -- Accessible outside the class through object reference.
Private -- Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes outside the assembly through member functions.
Let’s try to understand by a practical example:-
Interview Tip:-
The default access specifier for a class in internal. Mind it I mean class not class’s data members.






public class Class1


{


int i; //No Access specifier means private


public int j; // Public


protected int k; //Protected data


internal int m; // Internal means visible inside assembly


protected internal int n; //inside assembly as well as to derived classes outside assembly


static int x; // This is also private


public static int y; //Static means shared across objects


[DllImport("MyDll.dll")]


public static extern int MyFoo(); //extern means declared in this assembly defined in some other assembly


public void myFoo2()


{


//Within a class if you create an object of same class then you can access all data members through object reference even private data too


Class1 obj = new Class1();


obj.i =10; //Error can’t access private data through object.But here it is accessible.:)


obj.j =10;


obj.k=10;


obj.m=10;


obj.n=10;


// obj.s =10; //Errror Static data can be accessed by class names only


Class1.x = 10;


// obj.y = 10; //Errror Static data can be accessed by class names only


Class1.y = 10;


}


}






Now lets try to copy the same code inside Main method and try to compile


[STAThread]


static void Main()


{


//Access specifiers comes into picture only when you create object of class outside the class


Class1 obj = new Class1();


// obj.i =10; //Error can’t access private data through object.


obj.j =10;


// obj.k=10; //Error can’t access protected data through object.


obj.m=10;


obj.n=10;


// obj.s =10; //Errror Static data can be accessed by class names only


Class1.x = 10; //Error can’t access private data outside class


// obj.y = 10; //Errror Static data can be accessed by class names only


Class1.y = 10;


}


What if Main is inside another assembly


[STAThread]


static void Main()


{


//Access specifiers comes into picture only when you create object of class outside the class


Class1 obj = new Class1();


// obj.i =10; //Error can’t access private data through object.


obj.j =10;


// obj.k=10; //Error can’t access protected data through object.


// obj.m=10; // Error can’t access internal data outside assembly


// obj.n=10; // Error can’t access internal data outside assembly






// obj.s =10; //Errror Static data can be accessed by class names only


Class1.x = 10; //Error can’t access private data outside class


// obj.y = 10; //Errror Static data can be accessed by class names only


Class1.y = 10;


}




What is the difference between String and StringBuilder?


Both String and StringBuilder are classes used to handle strings.


The most common operation with a string is concatenation. This activity has to be performed very efficiently. When we use the "String" object to concatenate two strings, the first string is combined to the other string by creating a new copy in the memory as a string object, and then the old string is deleted. This process is a little long. Hence we say "Strings are immutable".


When we make use of the "StringBuilder" object, the Append method is used. This means, an insertion is done on the existing string. Operation on StringBuilder object is faster than String operations, as the copy is done to the same location. Usage of StringBuilder is more efficient in case large amounts of string manipulations have to be performed.




Nullabe Type in c#






One of the new features of C# 2.0 is nullable types. Now C# 2.0 allows you to assign null values to premitive types such as int, long, and bool.


The following code shows how to define an integer as nullable type and checks if the value of the integer is null or not.
/// Nullable types
///
public static void TestNullableTypes()
{
// Syntax to define nullable types
int? counter;
counter = 100;
if (counter != null)
{
// Assign null to an integer type
counter = null;
Console.WriteLine("Counter assigned null.");
}
else
{
Console.WriteLine("Counter cannot be assigned null.");
Console.ReadLine();
}
If you remove the "?" from int? counter, you will see a warning as following: "Cannot convert null to int besause it is a value type "




Covariance & Contravariance


Covariance basically means that the return value of a method that is referenced by your delegate can have a different return type than that specified by the delegate itself


Contravariance is kind of the same thing, but deals with the parameters rather than return types. Contravariance allows you to use delegate parameters who’s types are those that inherit from the parameter types used in the method the delegate references


Covariance




public class Car






{


}


public class Toyota : Car






{


}


class Demo






{


static void Main()


{


MyMethod abc = FunctionOne;


MyMethod xyz = FunctionTwo;


}




public delegate Car MyMethod();


public static Car FunctionOne()


{


return new Car();


}


public static Toyota FunctionTwo()


{


return new Toyota();


}


}






Contravariance




class Demo






{


public delegate void MyMethod(Toyota value);


static void Main(string[] args)


{


MyMethod abc = FunctionOne;


MyMethod xyz = FunctionTwo;


}


public static void FunctionOne(Car value)


{


}


public static void FunctionTwo(Toyota value)


{


}


}






















Ajax work process


Ajax web application follows the sequential steps below;


Courtesy: http://www.visualbuilder.com/ajax/tutorial/pageorder/8/






1. The JavaScript






function handEvent()t will be invoked when having an event occurred on the HTML element.






2. In the handEvent() method,an instance of XMLHttpRequest object is created.






3. The XMLHttpRequest object organizes an xml message within about the status of the HTML page,and then sends it to the web server.






4. After sending the request,the XMLHttpRequest object listens to the message from the web server






5. The XMLHttpRequest object parses the message returned from the web server and updates it into the DOM object




the steps invovled are -------------
Initial request by the browser – the user requests the particular URL.
The complete page is rendered by the server (along with the JavaScript AJAX engine) and sent to the client (HTML, CSS, JavaScript AJAX engine).
All subsequent requests to the server are initiated as function calls to the JavaScript engine.
The JavaScript engine then makes an XmlHttpRequest to the server.
The server processes the request and sends a response in XML format to the client (XML document). It contains the data only of the page elements that need to be changed. In most cases this data comprises just a fraction of the total page markup.
The AJAX engine processes the server response, updates the relevant page content or performs another operation with the new data received from the server. (HTML + CSS)








Covariance and Contravariance


Posted by raymondlewallen on December 28, 2006


So here is something that came up in a discussion I was having. It revolved around delegates and their parameter types because we were trying to find an easier way to solve an issue without having to write more code than we really wanted to. If you program entirely in VB or are not using .Net framework 2.0 with C#, then you are missing out on 2 features of delegates that are very useful: covariance and contravariance. Now I have personally spent, until very recently, the vast majority of my time in VB and Framework 1.1, so even though I knew about the features, I never fully understood what I could do with them and I was never able to make use of them until now when it came up as part of a way to solve a problem in a program that I am helping a friend with. He knew nothing of these new features, so maybe there are more of you out there that benefit from this, as it doesn’t seem to be well documented in easy to find places. Just for fun I tried to google "covariance" and a few other things with no success, so maybe putting this out there will make it easier for others to find. These are fine examples of how the languages continue to evolve and allow us to create more flexible, maintainable and efficient code.


Covariance basically means that the return value of a method that is referenced by your delegate can have a different return type than that specified by the delegate itself, so long as the return type of the method is a subclass of the return type of the delegate. In the example below, you can see that MyMethod returns Car, but xyz is calling FunctionTwo, which returns type Toyota. Because Toyota is derived from Car, this works.


Covariance


public class Car


{


}


public class Toyota : Car


{


}


class Demo


{


static void Main()


{


MyMethod abc = FunctionOne;


MyMethod xyz = FunctionTwo;


}




public delegate Car MyMethod();


public static Car FunctionOne()


{


return new Car();


}


public static Toyota FunctionTwo()


{


return new Toyota();


}


}




Contravariance is kind of the same thing, but deals with the parameters rather than return types. Contravariance allows you to use delegate parameters who’s types are those that inherit from the parameter types used in the method the delegate references. In the following example, you can see that FunctionOne specifies the Car type as the parameter, while the delegate has the signature that specifies Toyota. Contravariance allows this to happen.


Contravariance


class Demo


{


public delegate void MyMethod(Toyota value);


static void Main(string[] args)


{


MyMethod abc = FunctionOne;


MyMethod xyz = FunctionTwo;


}


public static void FunctionOne(Car value)


{


}


public static void FunctionTwo(Toyota value)


{


}








How ajax works ....................


Ajax web application follows the sequential steps below;


Courtesy: http://www.visualbuilder.com/ajax/tutorial/pageorder/8/






1. The JavaScript function handEvent()t will be invoked when having an event occurred on the HTML element.






2. In the handEvent() method,an instance of XMLHttpRequest object is created.






3. The XMLHttpRequest object organizes an xml message within about the status of the HTML page,and then sends it to the web server.






4. After sending the request,the XMLHttpRequest object listens to the message from the web server






5. The XMLHttpRequest object parses the message returned from the web server and updates it into the DOM object










----------------------------------------------------------------------------------




The core idea behind AJAX is to make the communication with the server asynchronous, so that data is transferred and processed in the background. As a result the user can continue working on the other parts of the page without interruption. In an AJAX-enabled application only the relevant page elements are updated, only when this is necessary.




In contrast, the traditional synchronous (postback-based) communication would require a full page reload every time data has to be transferred to/from the server. This leads to the following negative effects:


The user interaction with the application is interrupted every time a server call is needed, since a postback has to be made.
The user has to wait and look at blank screen during each postback.
The full page is being rendered and transferred to the client after each postback, which is time consuming and traffic intensive.
Any information entered by the user will be submitted to the server, perhaps prematurely.
The AJAX-enabled applications, on the other hand, rely on a new asynchronous method of communication between the client and the server. It is implemented as a JavaScript engine that is loaded on the client during the initial page load. From there on, this engine serves as a mediator that sends only relevant data to the server as XML and subsequently processes server response to update the relevant page elements.


the steps invovled are -------------
Initial request by the browser – the user requests the particular URL.
The complete page is rendered by the server (along with the JavaScript AJAX engine) and sent to the client (HTML, CSS, JavaScript AJAX engine).
All subsequent requests to the server are initiated as function calls to the JavaScript engine.
The JavaScript engine then makes an XmlHttpRequest to the server.
The server processes the request and sends a response in XML format to the client (XML document). It contains the data only of the page elements that need to be changed. In most cases this data comprises just a fraction of the total page markup.
The AJAX engine processes the server response, updates the relevant page content or performs another operation






Object Initialization Expressions
Object Initialization Expressions allow us to initialize an object without invoking its constructor and setting its properties.


If you take a simple customer class as follows:




public class Customer{ private int _id; public int Id { get { return _id; } set { _id = value; } } private string _name; public string Name { get { return _name; } set { _name = value; } } private string _city; public string City { get { return _city; } set { _city = value; } } public Customer() {} }
You can use Object Initialization Expressions in C# 3.0 to create a customer as follows:




Customer customer = new Customer{ Id = 1, Name="Dave",


City = "Sarasota" };
No where in the code above do we invoke a constructor or set any properties directly. The code above is equivalent to the following code:




Customer customer = new Customer();customer.Id = 1;customer.Name = "Dave";customer.City = "Sarasota";
You can create a list of customers as follows using Object Initialization Expressions in C# 3.0:




List listOfCustomers = new List { { Id = 1, Name="Dave", City="Sarasota" }, { Id = 2, Name="John", City="Tampa" }, { Id = 3, Name="Abe", City="Miami" } };


Extension methods


"As the name implies, extension methods extend existing .NET types with new methods."


Extension methods sound like a last resort form of extensibility since they are apparently hard to discover in the code, but nonetheless the idea is cool and could come in handy in the future. Obviously LINQ is handy :)


String.IsNullOrEmpty


One of the coolest things I love about the new string class in .NET 2.0 is the addition of the IsNullOrEmpty method. Now if that wasn't in there, we could do it with Extension Methods. In fact, since IsNullOrEmpty is currently a static method, we can go ahead and add the extension method anyway since it works on class instances. Let's go crazy and have it call Trim(), too :)




class Program{ static void Main(string[] args) { string newString = null; if (newString.IsNullOrEmpty()) { // Do Something } }}public static class Extensions{






public static bool IsNullOrEmpty(this string s) { // Notice I trim it too :) return (s == null || s.Trim().Length == 0); }}Anonymous Methods
I love Anonymous Methods in C# 2.0. The idea behind anonymous methods it to write methods inline to the code so you don't have to go through the trouble of declaring a formal named method. They are mainly used for small methods that don't require any need for reuse.


Instead of declaring a separate method IsAbe to find Abe in a list of strings:




class Program{ static void Main(string[] args) { List names = new List(); names.Add("Dave"); names.Add("John"); names.Add("Abe"); names.Add("Barney"); names.Add("Chuck"); string abe = names.Find(IsAbe); Console.WriteLine(abe); } public static bool IsAbe(string name) { return name.Equals("Abe"); }}
You can declare an anonymous method inline to save you the trouble:




class Program{ static void Main(string[] args) { List names = new List(); names.Add("Dave"); names.Add("John"); names.Add("Abe"); names.Add("Barney"); names.Add("Chuck"); string abe = names.Find(delegate(string name) { return name.Equals("Abe"); }); Console.WriteLine(abe); }}
It can get a lot fancier than that, but that is basically the gist. Declare the method inline to the code for easy stuff not needing reuse, because it saves some typing and puts the method closer to where it is being used which helps with maintenance.


Lambda Expressions
Lambda Expressions make things even easier by allowing you to avoid the anonymous method and that annoying statement block:




class Program{ static void Main(string[] args) { List names = new List(); names.Add("Dave"); names.Add("John"); names.Add("Abe"); names.Add("Barney"); names.Add("Chuck"); string abe = names.Find((string name)


=> name.Equals("Abe")); Console.WriteLine(abe); }}
Because Lambda Expressions are smart enough to infer variable types, I don't even have to explicity mention that name is a string above. I can remove it for even more simplicity and write it as such:




class Program{ static void Main(string[] args) { List names = new List(); names.Add("Dave"); names.Add("John"); names.Add("Abe"); names.Add("Barney"); names.Add("Chuck"); string abe = names.Find(name =>


name.Equals("Abe")); Console.WriteLine(abe); }}
Now there is no particular reason why I have to use name as my variable. Often developers will use 1 character variable names in Lambda Expressions just to keep things short. Here we replace name with p and all works the same.




class Program{ static void Main(string[] args) { List names = new List(); names.Add("Dave"); names.Add("John"); names.Add("Abe"); names.Add("Barney"); names.Add("Chuck"); string abe = names.Find(p => p.Equals("Abe")); Console.WriteLine(abe); }}




Silverlight Tip of the Day #48 – How to Implement a Combobox
With the release of Silverlight 2 RC0 there are three new controls we will be discussing that were not available for beta 2. The three new controls with a Tip of the Day for each include:


ProgressBar
ComboxBox
PasswordBox
For this tip we will be exploring the ComboBox control.


The following code below shows how to declare and size a combo box in your XAML:




ComboBoxItem>
ComboBoxItem>
ComboBoxItem>
ComboBox.Items>
ComboBox>


If you were to run this code you would see a combo box without any selected items:


Click the drop down button and you will see your three items displayed:


If you want to set a default selection for your combo box add the property IsSelected=”true” to any of your ComboBoxItems:




ComboBoxItem>
ComboBoxItem>
ComboBoxItem>
ComboBox.Items>
ComboBox>


If you run this code, you will see the 3rd item selected by default:






The ComboBox control also supports data binding. The following code below is an example implementation.


Few notes about this code:


By setting the DisplayMemberPath property you can specify which data item in your data you want displayed in the ComboBox. In our case below we set this to be the Name. We could have also set DisplayMemberPath =”Price” which would than show the car prices in the ComboBox.
Setting the SelectedIndex allows you to specify which item in the ComboBox you want selected.
I have attached an event to detect when the selection in the ComboBox has changed. The SelectedItem member of our ComboBox will return us the car that is selected at any given time.
using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Windows;using System.Windows.Controls;using System.Windows.Documents;using System.Windows.Input;using System.Windows.Media;using System.Windows.Media.Animation;using System.Windows.Shapes; namespace Password{ public partial class Page : UserControl { ComboBox _cars = new ComboBox(); public Page() { InitializeComponent(); List carList = new List(); carList.Add(new Car() { Name = "Ferrari", Price = 150000 }); carList.Add(new Car() { Name = "Honda", Price = 12500 }); carList.Add(new Car() { Name = "Toyota", Price = 11500 }); ComboBox cb = new ComboBox(); _cars.DisplayMemberPath = "Name"; _cars.ItemsSource = carList; _cars.SelectedIndex = 2; _cars.SelectionChanged += new SelectionChangedEventHandler(cb_SelectionChanged); MyCanvas.Children.Add(_cars); } void cb_SelectionChanged(object sender, SelectionChangedEventArgs e) { Car selectedCar = (Car) _cars.SelectedItem; int price = selectedCar.Price; string carName = selectedCar.Name; } } public class Car { public string Name { get; set; } public int Price { get; set; } }}--------------------------------------------


Generics are nothing new and have been part of .NET for over 5 years. Reference types and value types are core concepts in the CLR type system and these concepts have been the same since .NET was released – they are also nothing new. However, when I ask about these concepts during interviews, I often get a wide range in quality of the answers to these questions. If you get asked about these topics in an interview, be prepared to give great answers! You don’t have to give a textbook perfect memorized definition – but make sure you show that you fully understand and can apply the concepts to real-world development.


Question: why are generics such a big deal? I typically get answers discussing greater type safety and better performance. OK, the type safety one is pretty easy and straightforward. We had the ArrayList in .NET 1:


1: ArrayList list = new ArrayList();


2: list.Add(1);


3: list.Add(2);


4: list.Add("hello"); // compiler doesn't help me avoid!

When generics were introduced, we could declare a strongly-typed list of int’s to avoid this:


1: List list = new List();


2: list.Add(1);


3: list.Add(2);


4: list.Add("hello"); // compiler error!


So drilling into the second answer a little - *why* is performance better with generics? Often I hear, “you can avoid boxing and unboxing.” OK great! So what *specifically* is boxing and unboxing? (This is where people often start to struggle.) Boxing is the act of converting a value type to a reference type. If we look at line #2 of the first code sample above, we’re putting an Int32 (a value type) into an ArrayList which stores everything as System.Object (a reference type). Therefore, unboxing is the act of converting a reference type to a value type (e.g., if we were taking an item out of the ArrayList and having to cast: int num = (int)list[0];). So with boxing/unboxing, don’t focus on casting or sub-classes (they’re not directly relevant!) – focus on converting from reference types and values types.


Question: what’s the difference between a reference type and a value type? Just focus on the basics: Reference types are stored in the heap (which means they are garbage collected) and value types are stored in the stack (cannot be allocated on the GC heap). Reference types can be null; value types cannot be null. Reference type variables do not contain the value – it has a pointer to its value. A value type variable contains the value itself.


Question: how do you know if a type is a reference type or a value type? Is a DateTime a reference type or a value type? A String? If you’re creating your own Person data structure, how can you control whether it’s a value type or a reference type? The short answer: a “class” is a reference type and a “struct” is a value type. If you “View Definition” in Visual Studio on a DateTime, for example, you’ll see:


DateTime is a struct so it’s a value type. System.String is a class so it’s a reference type (plus, the fact that it can be null is also a tip off that it’s a reference type). So if you create your own data structure as a class, it will be a reference type (as a struct, a value type).


For further reading on reference types, value types, and boxing/unboxing, have a look at this article by Jeffrey Richter written in December 2000. These are core concepts in the .NET type system that are still just as relevant today as they were 10 years ago.


Let’s circle back to our original generics performance question. So far we have 3 assertions:


Generics result in better performance because you can avoid boxing/unboxing
Boxing/unboxing is the act of converting between reference types and value types
A “struct” is a value type (e.g., DateTime); a “class” is a reference type (e.g., String)
Question: given all three of these assertions, is performance *really* better with a generic List (string being a reference type) versus a non-generic list of strings? Answer: NO! Generics still provide *plenty* of benefit for these situations in terms of type-safety and allowing us to reduce noise in our code by avoiding having to cast objects (or code-gen objects if we want strongly-typed objects) – but a performance benefit is *not* on the list. However, if we’re talking about List or List (value types) then here is a significant performance improvement. Not only is the run-time performance benefit significantly better because we can avoid the expensive boxing/unboxing operations, but we also avoid making the GC do extra work by having to collect these boxed objects that were just heap-based wrappers around what were originally value types.


In fact, let’s say you use 5 different generic List in your application: List, List, List, List, List (where Foo and Bar are both reference types). What happens behind the scenes is that the JIT will actually produce 3 versions of the generic list. For each value type it will generate a totally strongly-typed version (so we’ll have 1 for List and 1 for List). Then it will generate a single generic List whose type gets re-used for all reference types behind the scenes (so it will get used for List, List, List). But it is providing you the type-safety features along with allowing you to avoid all of the ugly casting in your code.


New .NET technologies come and go and as professional developers we are constantly working to learn and stay up-to-date on these new technologies. However, we also have to make sure we stay grounded in the fundamentals that .NET is based on. If you ever end up in an interview with me, I trust that you’ll ace these questions. :) And, by the way, my company is hiring so if you’re interested, please contact me!


 
Asp.Net Framework Question Ans


what is .NET ?

.Net is a framework where we can develop different applications in a single environment using different type of languages


2)What is .NET Framework?


The .NET Framework has two main components: the common language runtime and

the .NET Framework class library.

You can think of the runtime as an agent that manages code at execution time,

providing core services such as memory management, thread management, and

remoting, while also enforcing strict type safety and other forms of code accuracy that

ensure security and robustness.

The class library, is a comprehensive, object-oriented collection of reusable types that

you can use to develop applications ranging from traditional command-line or

graphical user interface (GUI) applications to applications based on the latest

innovations provided by ASP.NET, such as Web Forms and XML Web services.


3) What is CLR?

The CLS is simply a specification that defines the rules to support language integration

in such a way that programs written in any language, yet can interoperate with one

another, taking full advantage of inheritance, polymorphism, exceptions, and other

features.

4) What are Generics in .Net framework 2.0?

Generics are related to the idea of Templates in C++. They permit classes, structs, interfaces, delegates, and methods to be parameterized by the types of data they store and manipulate. Without generics, general purpose methods or data structures (like Lists, Stacks, etc.) typically use the built-in Object type to store data of any type. While the use of the built-in Object type makes the implementation very flexible, it has drawbacks with regards to Performance and Type Safety.


5) What does the "EnableViewState" property do? Why would I want it on or off?

EnableViewState turns on the automatic state management feature that enables server controls to re-populate their values on a round trip without requiring you to write any code. This feature is not free however, since the state of a control is passed to and from the server in a hidden form field. You should be aware of when ViewState is helping you and when it is not.

6)What are the different modes for the sessionstates in the web.config file?

Off: Indicates that session state is not enabled.

Inproc: Indicates that session state is stored locally.

StateServer: Indicates that session state is stored on a remote server.

SQLServer: Indicates that session state is stored on the SQL Server.

7) Conditional Boating?
Bloating is an activity of performance improvement which is basically introduced in AJAX controls. The property UpdateMode is responsible for bloating for example the control updatepanel if you set UpdateMode Conditional then that clears your query.

8) What is the difference between Dataset.clone() and Dataset.copy()?
Using Dataset.clone() creates new instance of the same object.
Using Dataset.copy() copies content of data to another object wihtout creating new instance.

9) What is the difference between EVENTS and FUNCTIONS?
Event represents an action that is done to an object whereas Function represents an action that the object itself is doing.

10) what is the difference between application state and caching?
Application variable is the global variable specific to application but a
caching variable is specifc to page and time out.
Application variables exist as long as the application is alive. Whereas the cache has the Property of timeout which allows us to control the duration of the Objects so cached.
Another usefulness in caching is that we can define the way we cache our output since caching can be done in 3 ways -
a) Full Page - defined in page directrive
b) Partial Page - Eg - .ascx control
c) Data / Programatic caching. using the Properties of Cache object such as Cache.Insert .

NOTE:
Caching variable is specifc to page and time out
Application variable is the global variable specific to application

11) What is a Webcontrol?

Serves as the base class that defines the methods properties and events common to all controls in the System.Web.UI.WebControls namespace
A control is an object that can be drawn on to the Web Form to enable or enhance user interaction with the application. Examples of these controls include the TextBoxes Buttons Labels Radio Buttons etc. All these Web server controls are based on the System.Web.UI.Control class


12) Where do the Cookie State and Session State information be stored?

While executing the dynamic web page at the end of execution the value of session variables is calculated compressed and transmitted to the client via a Cookie. At this stage the state resides entirely and only on the client file system (or RAM).

Cookie Information will be stored in a txt file on client system under a
folder named Cookies. Search for it in your system you will find it.

Coming to Session State

As we know for every process some default space will be allocated by OS.

In case of InProc Session Info will be stored inside the process where our
application is running.

In case of StateServer Session Info will be stored using ASP.NET State Service.

In case of SQLServer Session info will be stored inside Database. Default DB
which will be created after running InstallSQLState Script is ASPState.

13) what is difference between key word &key filter?

The KeyFilter property is a new property that was added to control. Handling the KeyDown /KeyUp / KeyPress generates a callback on every key down which can be a great overhead if all you want is to handle a specific key down. That is way the new KeyFilter property was added. Basically it allows to define a filter which helps VWG generate callbacks only when you really need it. In the following sample code we have demonstrated the implementation of adding arrow behaviors to a set of text boxes which allows navigating between the fields.

Keyword is the reserved default words used by the language.


14) What is the difference between mechine.config and web.config?
Every asp.net application has web.cofig file. the settings given in this file is implied to that particular application only.But the settings given in machine.config file is implied to whole system.
Basically Machine.config file content the configuration setting for a particullar machine and Web.config file is used to store configure a particular web application. On any system there will be only one Machine.config file but Web.config file can number of time as per web application

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

Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performs a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address.

Response.Redriect means it can redirect the page which is located inside the application directory.server.transfer means it goes to another directory of the file.

Server.Transfer() send the request to server
Response.Redirect() sends the request to Browser
So If the Request is made for the location outside the Server it fails. so you need to use Respons.Redirect().

16) What is use of DataAdapater? and is it possible to add data from data reader directly to a dataset or a datatable?

DataAdapters purpose is to perform database queries and create dataTables containing the query results. Its also capable of writing changes made to the datataTables back to the database.

DataAdapter acts as a go-between providing a layer of abstraction between DataSet and the Physical Data sorce.


17) how many kinds of web services are there?

1) .Net web services

2) Java web services

3) brand X web services (built on SOAP)


18) what is name space for xml in asp.net

NameSpace : System.XML
Filde: System.Xml.dll


19) difference between remoting and web service in .net?explain with an example

in web service when the function which resides in the server is called by client side the message protocol used is soap and transfer protocol used is http.so all the message is first converted to xml format and serializes and use http transfer protocol for transfer to the server and again in server it gets deserialized and from the xml file it gets information about which fun ction is called by the client and what r the parameter.and agai return the value in xml format.As the message is passed in xml format it is platform independent

Remoting lets us enjoy the same power of web services when the platform is same.we can connect to the server directly over TCP and send binary data without having to do lots of conversion.


20) Explain the life cycle of an ASP .NET page.

Events in ASP.Net 1.1 & 2.0 :-



Application: BeginRequest
Application: PreAuthenticateRequest
Application: AuthenticateRequest
Application: PostAuthenticateRequest
Application: PreAuthorizeRequest
Application: AuthorizeRequest
Application: PostAuthorizeRequest
Application: PreResolveRequestCache
Application: ResolveRequestCache
Application: PostResolveRequestCache
Application: PreMapRequestHandler
Page: Construct
Application: PostMapRequestHandler
Application: PreAcquireRequestState
Application: AcquireRequestState
Application: PostAcquireRequestState
Application: PreRequestHandlerExecute
Page: AddParsedSubObject
Page: CreateControlCollection
Page: AddedControl
Page: AddParsedSubObject
Page: AddedControl
Page: ResolveAdapter
Page: DeterminePostBackMode
Page: PreInit
Control: ResolveAdapter
Control: Init
Control: TrackViewState
Page: Init
Page: TrackViewState
Page: InitComplete
Page: LoadPageStateFromPersistenceMedium
Control: LoadViewState
Page: EnsureChildControls
Page: CreateChildControls
Page: PreLoad
Page: Load
Control: DataBind
Control: Load
Page: EnsureChildControls
Page: LoadComplete
Page: EnsureChildControls
Page: PreRender
Control: EnsureChildControls
Control: PreRender
Page: PreRenderComplete
Page: SaveViewState
Control: SaveViewState
Page: SaveViewState
Control: SaveViewState
Page: SavePageStateToPersistenceMedium
Page: SaveStateComplete
Page: CreateHtmlTextWriter
Page: RenderControl
Page: Render
Page: RenderChildren
Control: RenderControl
Page: VerifyRenderingInServerForm
Page: CreateHtmlTextWriter
Control: Unload
Control: Dispose
Page: Unload
Page: Dispose
Application: PostRequestHandlerExecute
Application: PreReleaseRequestState
Application: ReleaseRequestState
Application: PostReleaseRequestState
Application: PreUpdateRequestCache
Application: UpdateRequestCache
Application: PostUpdateRequestCache
Application: EndRequest
Application: PreSendRequestHeaders
Application: PreSendRequestContent


------------

Page_Init -- Page Initialization

LoadViewState -- View State Loading

LoadPostData -- Postback data processing

Page_Load -- Page Loading

RaisePostDataChangedEvent -- PostBack Change Notification

RaisePostBackEvent -- PostBack Event Handling

Page_PreRender -- Page Pre Rendering Phase

SaveViewState -- View State Saving

Page_Render -- Page Rendering

Page_UnLoad -- Page Unloading


21) How to debug javascript or vbscript in .Net?
For debugging the client side script enable the debugging in IE.a. Open Microsoft Internet Explorer.b. On the Tools menu click Internet Options.c. On the Advanced tab locate the Browsing section clear the Disable script debugging check box and then click OK.d. Close Internet Explorer.

22) How to validate xmlschema in xml document?
One can validate the XML document againest a given schema using the .Net class under the package System.Xml.Schema; like using XMLSchemaValidator and XmlSchema.

23) What is the maximum number of cookies that can be allowed to a web site

- A maximum of 300 cookies can be stored on the user's system.
- No cookie can be larger than 4 kilobytes.
- No server or domain can place more than 20 cookies on a user's system. (One website can't hog all 300 cookies.)
- If you go beyond the maximum the browser will just discard old cookies to make room for the new ones.

24) What do you mean by authentication and authorization?
Authentication is the process of validating a user on the credentials (username and password) and authorization performs after authentication. After Authentication a user will be verified for performing the various tasks, It access is limited it is known as authorization.

25) What you thing about the WebPortal ?

Answer: Web portal is nothing but a page that allows a user to customize his/her homepage. We can use Widgets to create that portal we have only to drag and drop widgets on the page. The user can set his Widgets on any where on the page where he has to get them. Widgets are nothing but a page area that helps particular function to response. Widgets example are address books, contact lists, RSS feeds, clocks, calendars, play lists, stock tickers, weather reports, traffic reports, dictionaries, games and another such beautiful things that we can not imagine. We can also say Web Parts in Share Point Portal. These are one of Ajax-Powered.

26) How to start Outlook,NotePad file in AsP.NET with code ?
Answer: Here is the syntax to open outlook or notepad file in ASP.NET VB.NET Process.Start("Notepad.exe") Process.Start("msimn.exe"); C#.NET System.Diagnostics.Process.Start("msimn.exe"); System.Diagnostics.Process.Start("Notepad.exe");

27) What is the purpose of IIS ?
Answer: We can call IIS(Internet Information Services) a powerful Web server that helps us creating highly reliable, scalable and manageable infrastructure for Web application which runs on Windows Server 2003. IIS helps development center and increase Web site and application availability while lowering system administration costs. It also runs on Windows NT/2000 platforms and also for above versions. With IIS, Microsoft includes a set of programs for building and administering Web sites, a search engine, and support for writing Web-based applications that access database. IIS also called http server since it process the http request and gets http response.

28) What is the difference between Trace and Debug?
Trace and Debug - There are two main classes that deal with tracing - Debug and Trace. They both work in a similar way - the difference is that tracing from the Debug class only works in builds that have the DEBUG symbol defined, whereas tracing from the Trace class only works in builds that have the TRACE symbol defined. Typically this means that you should use System.Diagnostics.Trace.WriteLine for tracing that you want to work in debug and release builds, and System.Diagnostics.Debug.WriteLine for tracing that you want to work only in debug builds.

29) What is @@connection?

The Query Designer supports the use of certain SQL Server constants, variables, and reserved column names in the Grid or SQL panes. Generally, you can enter these values by typing them in, but the Grid pane will not display them in drop-down lists. Examples of supported names include:
· IDENTITYCOL If you enter this name in the Grid or SQL pane, the SQL Server will recognize it as a reference to an auto-incrementing column.
· Predefined global values You can enter values such as @@CONNECTIONS and @@CURSOR_ROW into the Grid and SQL panes.
· Constants (niladic functions) You can enter constant values such as CURRENT_TIMESTAMP and CURRENT_USER in either pane.
· NULL If you enter NULL in the Grid or SQL panes, it is treated as a literal value, not a constant.

30) what is diff between varcher and nvarchar?

VARCHAR is an abbreviation for variable-length character string. It's a string of text characters that can be as large as the page size for the database table holding the column in question. The size for a table page is 8,196 bytes, and no one row in a table can be more than 8,060 characters. This in turn limits the maximum size of a VARCHAR to 8,000 bytes.
The "N" in NVARCHAR means uNicode. Essentially, NVARCHAR is nothing more than a VARCHAR that supports two-byte characters. The most common use for this sort of thing is to store character data that is a mixture of English and non-English symbols — in m UTF-8). That said, NVARCHAR strings have the same length restrictions as their VARCHAR cousins — 8,000 bytes. However, since NVARCHARs use two bytes for each character, that means a given NVARCHAR can only hold 4,000 characters (not bytes) maximum. So, the amount of storage needed for NVARCHAR entities is going to be twice whatever you'd allocate for a plain old VARCHAR.
Because of this, some people may not want to use NVARCHAR universally, and may want to fall back on VARCHAR — which takes up less space per row — whenever possible.
may case, English and Japanese.

31)What is the maximum size of the file that I can upload using file upload control?
Ans. 4MB

32) What class all aspx pages inherits?

Ans.
System.Web.UI.Page

33) What is NewID?
Yes, newid() is unique. newid() returns a globally unique identifier. newid() will be unique for each call of newid().
Thus, newid() can be used as the value of a primary key of a sql server table. Values returned by newid() can be inserted into a primary key column of type "uniqueidentifier". Here is an example of a "uniqueidentifier" primary key column, with newid() used as the default value:
CREATE TABLE [tblUsers] (
[UserId] [uniqueidentifier] NOT NULL DEFAULT (newid()),
[UserName] [varchar](256) NOT NULL,
PRIMARY KEY ([UserId])

34) What is the use of AutoWireup in asp.net?

AutoEventWireup attribute is used to set whether the events needs to be automatically generated or not.
In the case where AutoEventWireup attribute is set to false (by default) event handlers are automatically required for Page_Load or Page_Init. However when we set the value of the AutoEventWireup attribute to true the ASP.NET runtime does not require events to specify event handlers like Page_Load or Page_Init.

35) how do you differentiate managed code and unmanaged code?

Managed code :Code that is executed by the CLR. Managed code provides information (i.e., metadata) to allow the CLR to locate methods encoded in assembly modules, store and retrieve security information, handle exceptions, and walk the program stack. Managed code can access both managed data and unmanaged data. Managed data—Memory that is allocated and released by the CLR using Garbage Collection. Managed data can only be accessed by managed code

Unmanaged Code:Unmanaged code is what you use to make before Visual Studio .NET 2002 was released. Visual Basic 6, Visual C++ , It is compiled directly to machine code that ran on the machine where you compiled it—and on other machines as long as they had the same chip, or nearly the same. It didn't get services such as security or memory management from an invisible runtime; it got them from the operating system. And importantly, it got them from the operating system explicitly, by asking for them, usually by calling an API provided in the Windows SDK. More recent unmanaged applications got operating system services through COM calls.



Managed Code is what Visual Basic .NET and C# compilers create. It compiles to Intermediate Language (IL) not to machine code that could run directly on your computer.Managed code runs in the Common Language Runtime.

Unmanaged code is what you use to make before Visual Studio .NET 2002 was released.It compiled directly to machine code that ran on the machine where you compiled it—and on other machines as long as they had the same chip or nearly the same.

-------

The code which is under control of CLR (Common Language Runtime) is called managed code.

The code which takes Operating System help while execution is called unmanaged code.

ASP.NET

What you thing about the WebPortal ?
Answer: Web portal is nothing but a page that allows a user to customize his/her homepage. We can use Widgets to create that portal we have only to drag and drop widgets on the page. The user can set his Widgets on any where on the page where he has to get them. Widgets are nothing but a page area that helps particular function to response. Widgets example are address books, contact lists, RSS feeds, clocks, calendars, play lists, stock tickers, weather reports, traffic reports, dictionaries, games and another such beautiful things that we can not imagine. We can also say Web Parts in Share Point Portal. These are one of Ajax-Powered.

2) How to start Outlook,NotePad file in AsP.NET with code ?
Answer: Here is the syntax to open outlook or notepad file in ASP.NET VB.NET Process.Start("Notepad.exe") Process.Start("msimn.exe"); C#.NET System.Diagnostics.Process.Start("msimn.exe"); System.Diagnostics.Process.Start("Notepad.exe");


3) What is the purpose of IIS ?
Answer: We can call IIS(Internet Information Services) a powerful Web server that helps us creating highly reliable, scalable and manageable infrastructure for Web application which runs on Windows Server 2003. IIS helps development center and increase Web site and application availability while lowering system administration costs. It also runs on Windows NT/2000 platforms and also for above versions. With IIS, Microsoft includes a set of programs for building and administering Web sites, a search engine, and support for writing Web-based applications that access database. IIS also called http server since it process the http request and gets http response.


4) What is main difference between GridLayout and FormLayout ?
Answer: GridLayout helps in providing absolute positioning of every control placed on the page.It is easier to devlop page with absolute positioning because control can be placed any where according to our requirement.But FormLayout is little different only experience Web Devloper used this one reason is it is helpful for wider range browser.If there is absolute positioning we can notice that there are number of DIV tags.But in FormLayout whole work are done through the tables.

5) How Visual SourceSafe helps Us ?
Answer: One of the powerful tool provided by Microsoft to keep up-to-date of files system its keeps records of file history once we add files to source safe it can be add to database and the changes ade by diffrenet user to this files are maintained in database from that we can get the older version of files to.This also helps in sharing,merging of files.


6) What is Partial Classes in Asp.Net 2.0?
partial classes mean that your class definition can be split into multiple physical files. Logically, partial classes do not make any difference to the compiler. During compile time, it simply groups all the various partial classes and treats them as a single entity.
Benefits of Partial Classes
One of the greatest benefits of partial classes is that they allow a clean separation of business logic and the user interface (in particular, the code that is generated by the Visual Studio Designer). Using partial classes, the UI code can be hidden from the developer, who usually has no need to access it anyway. Partial classes also make debugging easier, as the code is partitioned into separate files. This feature also helps members of large development teams work on their pieces of a project in separate physical files


7) What is an HTTP handler in ASP.NET? Can we use it to upload files? What is HttpModule?
The HttpHandler and HttpModule are used by ASP.NET to handle requests. Whenever the IIS Server recieves a request, it looks for an ISAPI filter that is capable of handling web requests. In ASP.NET, this is done by aspnet_isapi.dll. Same kind of process happens when an ASP.NET page is trigerred. It looks for HttpHandler in the web.config files for any request setting. As in machine.config default setting, the .aspx files are mapped to PageHandlerFactory, and the .asmx files are mapped to the WebServiceHandlerFactory. There are many requests processed by ASP.NET in this cycle, like BeginRequest, AuthenticateRequest, AuthorizeRequest, AcquireRequestState, ResolveRequestCache, Page Constructor, PreRequestHandlerExecute, Page.Init, Page.Load, PostRequestHandlerExecute, ReleaseRequestState, UpdateRequestCache, EndRequest, PreSendRequestHeaders, PreSendRequestContent.

Yes, the HttpHandler may be used to upload files.

HttpModules are components of .NET that implement the System.Web.IHttpModule interface. These components register for some events and are then invoked during the request processing. It implements the Init and the Dispose methods. HttpModules has events like AcquireRequestState, AuthenticateRequest, AuthorizeRequest, BeginRequest, Disposed , EndRequest, Error, PostRequestHandlerExecute, PreRequestHandlerExecute, PreSendRequestHeaders, ReleaseRequestState, ResolveRequestCache, UpdateRequestCache

8) How the find the N the maximum salary of an employee?

Ans.
SELECT MIN (SALARY )
FROM UEXAMPLE1
WHERE SALARY IN (SELECT DISTINCT TOP 4 SALARY FROM UEXAMPLE1 ORDER BY SALARY DESC)

9) What is @@connection?

The Query Designer supports the use of certain SQL Server constants, variables, and reserved column names in the Grid or SQL panes. Generally, you can enter these values by typing them in, but the Grid pane will not display them in drop-down lists. Examples of supported names include:
· IDENTITYCOL If you enter this name in the Grid or SQL pane, the SQL Server will recognize it as a reference to an auto-incrementing column.
· Predefined global values You can enter values such as @@CONNECTIONS and @@CURSOR_ROW into the Grid and SQL panes.
· Constants (niladic functions) You can enter constant values such as CURRENT_TIMESTAMP and CURRENT_USER in either pane.
· NULL If you enter NULL in the Grid or SQL panes, it is treated as a literal value, not a constant.


10) How to copy one total column data to another column?
Ans.
Update Set COLUMN2 = COLUMN1

Here copy column1 to column2

11) What is Global.asax?
Ans.
Global.asax is a file used to declare application-level events and objects. Global.asax is the ASP.NET extension of the ASP Global.asa file. ...
the ASP.NET page framework assumes that you have not defined any applicationa/Session events in the application.


12) What is boxing and UnBoxing?
Ans:
Boxing
Lets now jump to Boxing. Sometimes we need to convert ValueTypes to Reference Types also known as boxing. Lets see a small example below. You see in the example I wrote "implicit boxing" which means you don't need to tell the compiler that you are boxing Int32 to object because it takes care of this itself although you can always make explicit boxing as seen below right after implicit boxing.

Int32 x = 10; object o = x ; // Implicit boxing Console.WriteLine("The Object o = {0}",o); // prints out 10 //----------------------------------------------------------- Int32 x = 10; object o = (object) x; // Explicit Boxing Console.WriteLine("The object o = {0}",o); // prints out 10

Unboxing
Lets now see UnBoxing an object type back to value type. Here is a simple code that unbox an object back to Int32 variable. First we need to box it so that we can unbox.
Int32 x = 5; object o = x; // Implicit Boxing x = o; // Implicit UnBoxing
So, you see how easy it is to box and how easy it is to unbox. The above example first boxs Int32 variable to an object type and than simply unbox it to x again. All the conversions are taking place implicitly. Everything seems right in this example there is just one small problem which is that the above code is will not compile. You cannot Implicitly convert a reference type to a value type. You must explicitly specify that you are unboxing as shown in the code below.
Int32 x = 5; object o = x; // Implicit Boxing x = (Int32)o; // Explicit UnBoxing
Lets see another small example of unboxing.
Int32 x = 5; // declaring Int32 Int64 y = 0; // declaring Int64 double object o = x; // Implicit Boxing y = (Int64)o; // Explicit boxing to double Console.WriteLine("y={0}",y);
This example will not work. It will compile successfully but at runtime It will generate an exception of System.InvalidCastException. The reason is variable x is boxed as Int32 variable so it must be unboxed to Int32 variable. So, the type the variable uses to box will remain the same when unboxing the same variable. Of course you can cast it to Int64 after unboxing it as Int32 as follows:
Int32 x = 5; // declaring Int32 Int64 y = 0; // declaring Int64 double object o = x; // Implicit Boxing y = (Int64)(Int32)o; // Unboxing and than casting to double Console.WriteLine("y={0}",y);


13) What is WPF? WCF?
Windows Presentation Foundation, it is to develop the applications which contains Rich Graphics. Example Google Earth.
Windows Communication Foundation is the framework to develop the SOA (Service Oriented Architecture) based applications. Which applications can be communicated with any applications that are developed using any other technologies?

14) what is web service?

Web services are frequently just Web APIs that can be accessed over a network, such as the Internet, and executed on a remote system hosting the requested services
The W3C Web service definition encompasses many different systems, but in common usage the term refers to clients and servers that communicate over the HTTP protocol used on the Web. Such services tend to fall into one of two camps: Big Web Services and RESTful Web Services.
"Big Web Services" use XML messages that follow the SOAP standard and have been popular with traditional enterprise. In such systems, there is often machine-readable description of the operations offered by the service written in the Web Services Description Language (WSDL). The latter is not a requirement of a SOAP endpoint, but it is a prerequisite for automated client-side code generation in many Java and .NET SOAP frameworks (frameworks such as Spring, Apache Axis2 and Apache CXF being notable exceptions). Some industry organizations, such as the WS-I, mandate both SOAP and WSDL in their definition of a Web service.

15) How to know whether the Table ‘xyz’ exists or not?
IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[Country_Master]') AND type in (N'U'))

16) Difference between an Interface and Abstract class?
Ans.
(1) An abstract class may contain complete or
incomplete methods. Interfaces can contain only the
signature of a method but no body. Thus an abstract class
can implement methods but an interface can not implement
methods.
(2) An abstract class can contain fields,
constructors, or destructors and implement properties. An
interface can not contain fields, constructors, or
destructors and it has only the property's signature but no
implementation.
(3) An abstract class cannot support multiple
inheritance, but an interface can support multiple
inheritance. Thus a class may inherit several interfaces
but only one abstract class.
(4) A class implementing an interface has to
implement all the methods of the interface, but the same is
not required in the case of an abstract Class.
(5) Various access modifiers such as abstract,
protected, internal, public, virtual, etc. are useful in
abstract Classes but not in interfaces.
(6) Abstract classes are faster than interfaces.

17) What is IL?
Ans.
A language that is generated from programming source code, but that cannot be directly executed by the CPU. Also called "bytecode," "p-code," "pseudo code" or "pseudo language," the intermediate language (IL) is platform independent. It can be run in any computer environment that has a runtime engine for the language.

In order to execute the intermediate language program, it must be interpreted a line at a time into machine language or compiled into machine language and run.

18) What is difference between VBScript and JavaScript?
Ans.
Vbscript will be run on IE
JavaScript runs on any browser
Vbscript is developed by ms
Java script by Sunmicrosystems
Vb not case sensitive
Java is case sensitive


19) What is ObjRef object in remoting?

ObjRef is a searializable object returned by Marshal() that knows about location of the remote object, host name, port number, and object name.


20) How can we create custom controls in ASP.NET?

Custom controls are user defined controls. They can be created by grouping existing controls, by deriving the control from System.Web.UI.WebControls.WebControl or by enhancing the functionality of any other custom control. Custom controls are complied into DLL’s and thus can be referenced by as any other web server control.

Basic steps to create a Custom control:

1. Create Control Library
2. Write the appropriate code
3. Compile the control library
4. Copy to the DLL of the control library to the project where this control needs to be used
5. The custom control can then be registered on the webpage as any user control through the @Register tag.

21) What is the Pre-Compilation feature of ASP.NET 2.0?

Previously, in ASP.NET, the pages and the code used to be compiled dynamically and then cached so as to make the requests to access the page extremely efficient. In ASP.NET 2.0, the pre-compilation feature is used with which an entire site is precompiled before it is made available to users.

There is a pre-defined folder structure for enabling the pre-compilation feature:

* App_Code: stores classes
* App_Themes: stores CSS files, Images, etc.
* App_Data: stores XML files, Text Files, etc.

It is a process where things that can be handled before compilation are prepared in order to reduce the deployment time, response time, increase safety. It’s main aim to boost performance.

It also helps in informing about the compilation failures.

During development, it allows you to make changes to the web pages and reuse it using the same web browser to validate the changes without compiling the entire website.

During deployment, it generates the entire website folder structure in the destination. All the static files are copied to the folder and bin directory would later on contain the compiled dll.


* App_GlobalResources: stores all the resources at global level E.g. resx files, etc
* App_LocalResources: stores all the resources at local/Page level

22) What is the purpose of Server.MapPath method in Asp.Net?

In Asp.Net Server.MapPath method maps the specified relative or virtual path to the corresponding physical path on the server. Server.MapPath takes a path as a parameter and returns the physical location on the hard drive. Syntax

Suppose your Text files are located at D:\project\MyProject\Files\TextFiles

If the root project directory is MyProject and the aspx file is located at root then to get the same path use code

//Physical path of TextFiles
string TextFilePath=Server.MapPath("Files/TextFiles");

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.Output.Write() allows you to write formatted output.
2. What methods are fired during the page load?

Init() - when the page is instantiated
Load() - when the page is loaded into server memory
PreRender() - the brief moment before the page is displayed to the user as HTML
Unload() - when page finishes loading.
3. When during the page processing cycle is ViewState available?

After the Init() and before the Page_Load(), or OnLoad() for a control.
4. What namespace does the Web page belong in the .NET Framework class hierarchy?

System.Web.UI.Page
5. Where do you store the information about the user’s locale?

CodeBehind is relevant to Visual Studio.NET only.
6. What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?

CodeBehind is relevant to Visual Studio.NET only.
7. What is the Global.asax used for?

The Global.asax (including the Global.asax.cs file) is used to implement application and session level events.
8. What are the Application_Start and Session_Start subroutines used for?

This is where you can set the specific variables for the Application and Session objects.
9. Whats an assembly?

Assemblies are the building blocks of the .NET framework;
10. Whats MSIL, and why should my developers need an appreciation of it if at all?

MSIL is the Microsoft Intermediate Language. All .NET compatible languages will get converted to MSIL. MSIL also allows the .NET Framework to JIT compile the assembly on the installed computer.
11. Which method do you invoke on the DataAdapter control to load your generated dataset with data?

The Fill() method.
12. Can you edit data in the Repeater control?

No, it just reads the information from its data source.
13. Which template must you provide, in order to display data in a Repeater control?

ItemTemplate.
14. Name two properties common in every validation control?

ControlToValidate property and Text property.
15. What base class do all Web Forms inherit from?

The Page class.
16. What is the difference between Server.Transfer and Response.Redirect? Why would I choose one over the other?

Server.Transfer transfers page processing from one page directly to the next page without making a round-trip back to the client's browser. This provides a faster response with a little less overhead on the server. Server.Transfer does not update the clients url history list or current url. Response.Redirect is used to redirect the user's browser to another page or site. This performas a trip back to the client where the client's browser is redirected to the new page. The user's browser history list is updated to reflect the new address
17. What is ViewState?

ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.
18. What is the lifespan for items stored in ViewState?

Item stored in ViewState exist for the life of the current page. This includes postbacks (to the same page).
19. What does the "EnableViewState" property do? Why would I want it on or off?

It allows the page to save the users input on a form across postbacks. It saves the server-side values for a given control into ViewState, which is stored as a hidden value on the page before sending the page to the clients browser. When the page is posted back to the server the server control is recreated with the state stored in viewstate.
20. What are the different types of Session state management options available with ASP.NET?

ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the session in memory on the web server. This requires the a "sticky-server" (or no load-balancing) so that the user is always reconnected to the same web server. Out-of-Process Session state management stores data in an external data source. The external data source may be either a SQL Server or a State Server service. Out-of-Process state management requires that all objects stored in session are serializable.

Friday, November 26, 2010

Asp.Net Question Answer

What is the difference between Finalize() and Dispose()?

Dispose() is called by as an indication for an object to release any unmanaged resources it has held.
Finalize() is used for the same purpose as dispose however finalize doesn’t assure the garbage collection of an object.
Dispose() operates determinalistically due to which it is generally preferred

______________
What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?

XML Web services are more restricted than objects exposed over .NET Remoting.
XML Web services support open standards that target cross-platform use.
XML Web services are generally easier to create and due to the restricted nature of XML Web services, the design issues are simplified.
XML Web services support only SOAP message formatting, which uses larger XML text messages.
Communication with .NET Remoting can be faster than XML Web service communication with a binary formatter.
XML Web services are designed for use between companies and organizations.
XML Web services don't require a dedicated hosting program because they are always hosted by ASP.NET.
Consumers can use XML Web services just as easily as they can download HTML pages from the Internet. Thus there's no need for an administrator to open additional ports on a firewall as they work through MS-IIS and ASP.NET

______________
Explain how to add controls dynamically to the form using C#.NET.

The following code can be called on some event like page load or onload of some image or even a user action like onclick

protected void add_button(Button button)
{
try
{
panel1.Controls.Add(button); // Add the control to the container on a page
}
catch (Exception ex)
{
label1.Text += ex.Message.ToString();
}
}

______________
Why is an Object Pool required?

The request for the creation of an object is served by allocating an object from the pool.

This reduces the overhead of creating and re-creating objects each time an object creation is required.

C#.Net - Why is an object pool required?

To enhance performance and reduce the load of creating new objects, instead re using existing objects stored in memory pool. Object Pool is a container of objects that are for use and have already been created. Whenever an object creation request occurs, the pool manager serves the request by allocating an object from the pool. This minimizes the memory consumption and system's resources by recycling and re-using objects. When the task of an object is done, it is sent to the pool rather than being destroyed. This reduces the work for garbage collector and fewer memory allocations occur.

______________

What are ILDASM and Obfuscator in NET?

ILDASM (Intermediate Language Disassembler)
De-Compilation is the process of getting the source code from the assembly.
ILDASM is a de-compiler provided by Microsoft.
This ILDASM converts an assembly to instructions from which source code can be obtained.
Obfuscated code is source code or intermediate language that is very hard to read and understand.
An obfuscator is a medium of making a program difficult to understand.
The way the code runs remains unaffected although the obfuscator makes it harder to hack the code and hijack the program.
C#.Net - What is ILDASM and Obfuscator in NET?

ILDASM is MSIL Disassmbler. This take a portable executable (PE), which consists of MSIL code, and creates a text file which can then be used as an input for ILASM.exe, which is MSIL assembler. ILDASM can parse any .Net dll or exe and shows information in human readable form. It displays MSIL, namespaces, types and interfaces. It's normally used to examine assemblies and understand what the assembly is capable of.

Obfuscator is a tool to protect .Net assemblies and exe files. The tool renames all possible symbols, types, interfaces, namespaces etc into meaningless values and removes all unnecessary information. This reduces the size of the assemblies and also helps in protecting the code. It's normally used to protect the assemblies from exposing information for reverse engineering.

_____________

What is the GAC? What problem does it solve?

Global Assembly Cache (GAC):

Any system that has the CLR (common language runtime) installed, has a machine-wide code cache known as GAC.

Assemblies deployed in the global assembly cache need to have a strong name.

The Global Assembly Cache tool (Gacutil.exe), provided by the .NET Framework SDK can be used to deploy assemblies to GAC.


Disabled and Unabled Control Using C#

I'm converting one of my function in Vb6.0 to C#.net this function will allow the user to disabled and enabled Controls in the form, you can also add a if statement for other Controls in the form. :)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
test t = new test();

private void button1_Click(object sender, EventArgs e)
{

t.tagControl(Form.ActiveForm);
}

private void button2_Click(object sender, EventArgs e)
{
t.tagControl(Form.ActiveForm);
}
}
}



using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
test t = new test();

private void button1_Click(object sender, EventArgs e)
{

t.tagControl(Form.ActiveForm);
}

private void button2_Click(object sender, EventArgs e)
{
t.tagControl(Form.ActiveForm);
}
}
}


Search for Type Of Materials