Thursday, 4 March 2010

Design Patterns Links

http://www.c-sharpcorner.com/UploadFile/questpond/DP109212008014904AM/DP1.aspx

http://www.dofactory.com/Patterns/Patterns.aspx

http://www.techfaq360.com/oops_interview_questions.jsp

http://www.codeproject.com/KB/aspnet/SoftArchInter1.aspx

Wednesday, 3 March 2010

FAQ's - DotNet Framework

What is CLR? Who loads the CLR into a process?

Common Language Runtime - It is the implementation of CLI(Common Language Infrastructure). The core runtime engine in the Microsoft .NET Framework for executing applications. The common language runtime supplies managed code with services such as cross-language integration, code access security, object lifetime management, resouce management, type safety, pre-emptive threading, metadata services (type reflection), and debugging and profiling support. The ASP.NET Framework and Internet Explorer are examples of hosting CLR. The CLR is a multi-language execution environment. There are currently over 15 compilers being built by Microsoft and other companies that produce code that will execute in the CLR. 
The CLR is described as the "execution engine" of .NET. It's this CLR that manages the execution of
programs. It provides the environment within which the programs run. The software version of .NET is
actually the CLR version.

What is an Application Domain?Application domains help in providing isolation, unloading, and security boundaries for executing managed code. These Application Domains are very similar to the operating system concept Process. The isolation of applications is achieved using Application Domains. This will help them to see that they do not affect each other.

What is a GC?In C#, Garbage Collector will collect variables(Weak & no reference objects) from generations. Initially, when a variable is declared, it will be into generation 0, When GC is collecting variables for garbage collection, it will move all variables which are uncollected to its higher generation. So, all uncollected variables in Generation 0 will move to Generation 1 and Generation 1 variables to Generation 2. Currently Garbage collector has 3 generations, Generation 0,Generation 1 and Generation 2.You can find maximum number of generations that CLR will have by using1.System.GC.MaxGeneration

What is a CTS and CLS?
• CTS (Common Type System)It defines “How object should be declared”. CLS is the subset of CTS.


• CLS (Common Language Specification)It provides, set of specification TO BE adhered by new language writer/compiler writer for .Net Framework to ENSURE interoperability. ‘cause .net supports 32 languages.For example Asp.Net application written in C#.Net language. Now we can refer any other DLL which has been written in any other language supported by .Net Frame Work.

What is GAC?The Global Assembly Cache (GAC) stores assemblies specifically designated to be shared by several applications on the computer. Assemblies deployed in the global assembly cache must have a strong name. When an assembly is added to the global assembly cache, integrity checks are performed on all files that make up the assembly. GAC physically creates directories for each version of the assembly. The Global Assembly Cache (GAC), when viewed using Explorer, has its view rendered in a special manner by the OS shell. When an Assembly is added to GAC these are the attributes that it takes.
• Assembly Name – Name of the Assembly
• Version – Version [Major-Minor-Revision-Build]
• Culture – Culture will be null for normal Assembly
• Public Key Token - This is a 64-bit hash of the public key which makes the assembly name unique.
• Processor Architecture – Either MSIL or x86

What is an Assembly?
An assembly is a basic building block for any application in the .NET Framework. It is a 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 (CLR) with the information it needs to be aware of type implementations. During runtime, a type does not exist outside the context of an assembly.
The contents of an assembly are the following.
• CIL – Common Intermediate Language (formerly MSIL - Microsoft Intermediate Language)
• Assembly Manifest – The Assembly Manifest has the information like Name, Version number, Culture, Strong Name information, etc.
• Type Metadata
• Resources

What are the different types of assemblies?
1) Private Assembly
2) Public/Shared Assembly
3) Satellite Assembly

What is a Shared Assembly?
Shared Assemblies are kept in Global Assembly Cache. Client application using Shared Assemblies need not have its own copy of dll. Shared Assemblies are present in C:\WINDOWS\assembly folder.
Steps to create Shared Assembly:
1. Create a .dll file. (Here i am using my existing HappyNewYear.dll)2. Now let me create unique assembly name using SN utility(Shared Name utility).  The syntax for it is: sn -k filename.snk
Here sn stands for strong name, -k stands for key and key is stored in filename.snk .


What is a Satellite Assembly?
Satellite Assembly is a .NET Framework assembly containing resources specific to a given language. Using a satellite assembly, we can place resources of different languages in different assemblies and the correct assembly is loaded into memory only if the user elects to view the application in that language.

What is a .NET module? How is a .NET module different from an Assembly?
A .NET module is a portable executable file of type.dll or .exe consisting of one or more classes. This is similar to a .NET assembly which consists of classes, namespaces, etc.
A .NET module can not be deployed alone. It has to be linked into an assembly. This can be done by using compiler’s /add module switch (if the compiler supports it), al.exe, or in .NET Framework 2.0, link.exe.

What is CodeDOM in .NET used for?
CodeDOM is an API that helps in creating and compiling a programming structure at Runtime. Creating a programming structure involves creation of Namespace, Type – Class, Interface and even methods at the Runtime. The implementation of CodeDOM can be divided in the two ways shown below. The namespace for the CodeDOM is System.CodeDOM.
• Compiling or Building the Programs at the Runtime
• Using CodeDOM for generating a Program structure

Meaning for Assembly Version?
1:2:3:4 -- (Major : Minor : Build : Revision)

Install/Uninstall the assembly in GAC or converting a private assembly as a shared assembly?
Ex: gacutil /i assemblyname.dll (Add)
gacutil /u assemblyname.dll (Add)

FAQ's - SQL Server

FAQ's - ASP.NET

Life cycle of ASP.NET 2.0 Page ?
Life cycle of the page is defined as the list of events that get fired from the Page initialization to page rendering. The list of events is illustrated along with the descriptions.
Name of the Event - When does the event fire
PreInit - Occurs at the beginning of page initialization.
Init - Occurs when the server control is initialized, which is the first step in its lifecycle.
InitComplete - Occurs when page initialization is complete.
PreLoad - Occurs before the page Load event.
Load - Occurs when the server control is loaded into the Page object.
PreRender - Occurs after the Control object is loaded, but prior to rendering.
PreRenderComplete - Occurs before the page content is rendered.
SaveStateComplete - Occurs after the page has completed saving all view state and control state information for the page and controls on the page.
LoadComplete - Occurs at the end of the load stage of the page's life cycle.
Unload - Occurs when the server control is unloaded from memory.

What is the Pre-Compilation feature of ASP.NET 2.0? How does the new folder structure help for the same?
By default, ASP.NET Web pages and code files are compiled dynamically when users first request a resource such as a page from the Web site. After pages and code files have been compiled the first time, the compiled resources are cached, so that subsequent requests to the same page are extremely efficient. This was in previous versions of ASP.NET, but in ASP.NET 2.0 we have a feature called as pre-compilation. With this, ASP.NET can also pre-compile an entire site before it is made available to users. We have some pre-defined folder structures for enabling this feature of pre-compilation. Let us list down some of the folders with a brief description of what they are meant for.
• App_Code – meant for storing classes
• App_Themes – meant for storing CSS files, Images, etc.
• App_Data –meant for storing XML files, Text Files, etc.
• App_GlobalResources – meant for storing all the resources at global level E.g. resx files, etc
• App_LocalResources – meant for storing all the resources at local/Page level

What is the class name for accessing the Configuration in .NET 2.0?
The class name used for accessing configuration in .NET 2.0 is ConfigurationManager. The ConfigurationManager class is a static class which has all the methods for accessing application configuration file
. For web applications we have WebConfigurationManager class. The WebConfigurationManager allows us to access machine and application information.

What is Authentication in ASP.NET?
Authentication is the process of identifying a user with identification credentials like User name and Password with some authority. Generally after authentication the system gets to know who the user is. ASP.Net has some authentication providers. Let us discuss some of them.
Windows Authentication Provider - Windows authentication in conjunction with Microsoft Internet Information Services (IIS) authentication to secure ASP.NET applications
Forms Authentication Provider – An application-specific login form and performs authentication using user code.
Passport Authentication provider – Centralized authentication service provided by Microsoft offers a single login and core profile service for member sites.

What is Authorization in ASP.NET?
Authorization determines whether an identity/user should be granted access to a specific resource. Authorization requires that the authentication is already done. There are 2 ways to authorize access to a given resource:
• File authorization - File authorization is performed by the FileAuthorizationModule. It checks the access control list (ACL) of the .aspx or .asmx handler file to determine whether a user should have access to the file.
• URL authorization - URL authorization is performed by the UrlAuthorizationModule, which maps users and roles to URLs in ASP.NET applications.
Ex:

<[allow|deny] users roles verbs />


What is the difference between Response.Redirect() and Server.Transfer()?
Redirect Method:
- Client knows about the redirection of the URL.
- ASP.net can force reauthorization by using the Redirect method instead of the Transfer method.
- Response.Redirect is little bit slower, but it retains the new URL.
- Cannot use HTTPContext.Items.

Transfer Method:
- Client does not know anything about the transfer. It appears to be the same old URL for the client.
- ASP.NET does not verify that the current user is authorized to view the resource delivered by the Transfer method. You need to have a Custom logic for the same.
- Server Transfer is faster as it reduces 1 less trip to the client.
- HTTPContext.Items are accessible.

FAQ's - C#


Does C# support multiple-inheritance?
No.

Who is a protected class-level variable available to?
It is available to any sub-class (a class inheriting this class).

Are private class-level variables inherited?
Yes, but they are not accessible. Although they are not visible or accessible via the class interface, they are inherited.

Describe the accessibility modifier “protected internal”?
It is available to classes that are within the same assembly and derived from the specified base class.

What’s the top .NET class that everything is derived from?
System.Object.

What is the difference between Int.Parse , Convert.ToInt() and Int.TryParse()?
Int32.Parse Method
Converts the string representation of a number to its 32-bit signed integer equivalent.
-When s is a null reference, it will throw ArgumentNullException.
-If s is other than integer value, it will throw FormatException.
-When s represents a number out of range, it will throw OverflowException.

Convert.ToInt32(string)
Converts the specified string representation of 32-bit signed integer equivalent. This calls in turn Int32.Parse () method.
-When s is a null reference, it will return 0 rather than throw ArgumentNullException.
-If s is other than integer value, it will throw FormatException.
-When s represents a number out of range, it will throw OverflowException.

Int32.TryParse Method
Converts the specified string representation of 32-bit signed integer equivalent to out variable, and returns true if it is parsed successfully, false otherwise.
-When s is a null reference, it will return 0.
-If s is other than an integer value, the out variable will have 0.
-When s represents a number out of range, the out variable will have 0.


What does the term immutable mean?
The data value may not be changed.
Note: The variable value may be changed, but the original immutable data value was discarded and a new data value was created in memory.

What’s the difference between System.String and System.Text.StringBuilder classes?
System.String is immutable. System.StringBuilder was designed with the purpose of having a mutable string where a variety of operations can be performed.

What’s the advantage of using System.Text.StringBuilder over System.String?
StringBuilder is more efficient in cases where there is a large amount of string manipulation. Strings are immutable, so each time a string is changed, a new instance in memory is created.

Can you store multiple data types in System.Array?
No.

What’s the difference between the System.Array.CopyTo() and System.Array.Clone()?
The Clone() method returns a new array (a shallow copy) object containing all the elements in the original array. The CopyTo() method copies the elements into another existing array. Both perform a shallow copy. A shallow copy means the contents (each array element) contains references to the same object as the elements in the original array. A deep copy (which neither of these methods performs) would create a new instance of each element's object, resulting in a different, yet identacle object.

How can you sort the elements of the array in descending order?
By calling Sort() and then Reverse() methods.

What’s the .NET collection class that allows an element to be accessed using a unique key?
HashTable.

What class is underneath the SortedList class?
A sorted HashTable.

Will the finally block get executed if an exception has not occurred?­
Yes.

What’s the C# syntax to catch any possible exception?
A catch block that catches the exception of type System.Exception. You can also omit the parameter data type in this case and just write catch {}.

Can multiple catch blocks be executed for a single try statement?
No.
Once the proper catch block processed, control is transferred to the finally block (if there are any).

Explain the three services model commonly know as a three-tier application?
Presentation (UI), Business (logic and underlying code) and Data (from storage or other sources).

What is the difference between int and Int32?
Int32 is a class of namespace System. Keyword "int" is the alias of the class. So there is no real difference.

What does mutable and immutable means?
Immutable objects (read-only) are objects whose value cannot be modified once it has been created. Methods that appear to modify an immutable object actually return a new object that contains the modification (the previous object remains in memory until garbage collected).
Mutable Objects are objects whose value can be modified.

What is the difference between String class and StringBuilder class? Which one is better?
String Class is immutable and StringBuilder class is mutable. If the object has many operations involved then StringBuilder class is a better option.

What are delegates?
A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.

What is difference between delegates and Events?
A delegate is a reference to a method. A delegate is raw in its nature, but an event is hooked up with a control; it acts based on the behaviour of the control. An event is a delegate, but a delegate is not an event. Event = Delegate + Event handling logic.

What is a partial class?
A Partial class is a class that can be split into two or more classes. This means that a class can be physically separated into other parts of the class within the same namespace. All the parts must use the partial keyword. All the other classes should also have the same access modifier. At the compile time, all the partial classes will be treated as a single class. Let us list some advantages of having partial classes.
• Allows a clean separation of business logic layer and the user interface.
• The UI code can be hidden from the developer.
• Makes the debugging easier.

What is a Sealed Class? Where is it used?
A sealed class is a class for which there will be no derived class. The keyword sealed ensures no overriding of members.
In general all the API and framework classes are made to be sealed classes.

What are Generics?
Generics are classes, structures, interfaces, and methods that have placeholders (type parameters) for one or more of the types they store or use. Using Generics, the type safety check burden will be on the compiler rather than developer. Hence, the Developer needs to write the code explicitly for checking type safety.
Ex:
public class Generic
{
public T Field;
}
Generic g = new Generic();
g.Field = "Some Value";

Example shows a simple example of Generics. The generic class defined has a field of the type T. The type T is initialized to be string.


http://en.csharp-online.net/CSharp_FAQ:_Are_CSharp_constructors_inherited

http://blogs.crsw.com/mark/articles/252.aspx

http://www.devbistro.com/tech-interview-questions/.NET.jsp

http://blogs.crsw.com/mark/articles/254.aspx

http://www.interviewqsn.com/asp_net-2008-features.html

http://msdotnetsupport.blogspot.com/2007/11/22-new-features-of-visual-studio-2008.html



Sudhakar has given:



http://venkataspinterview.blogspot.in/2008/07/aspnet-interview-questions.html

http://www.aspdotnet-suresh.com/











DotNet Framework - Understanding the Application Domains and CLR host

Introduction
Process was the basic unit of execution and isolation for running applications in Traditional Windows application development. The advantage with the model was that each application running was loaded into a separate process that automatically isolated each application from the other. For example, if an error occurred in an application, that would not affect the other applications running on the system. Also, process is defined as a security boundary that prevents applications from talking directly with each other.

This worked fine with the Traditional windows development. Things have changed a bit with the arrival of .NET runtime. The concept is much more enhanced with a new entity called "Application Domain." Application Domains are much like processes. The Application Domain is designed to act like a security boundary and confines errors and faults to a specific domain. Although, it is similar to the process, the Application Domain has some different characteristics.

What are Application Domains?
Let us understand the Application Domains (By differentiating them with a process wherever necessary).

·Application Domain is much lighter than the traditional Windows based processes.

·Application Domains are perfect for application scenarios as they require isolation without the heavy overhead associated with the traditional application process.

·The Application Domain is a virtual process that isolates applications. This guarantees that each application is independent and is not able to directly access resources within another domain.

·Application domain can have a domain level

Application Domains and CLR Hosts – Loading Default Domains
The Common Language Runtime (CLR) is the foundation upon which the Microsoft .NET strategy is built. The CLR provides an execution environment that manages running code and provides services that make software development easier. In order to start running managed code in a process, the CLR must be loaded and initialized. The host is responsible for loading the CLR. Most hosts consist of both unmanaged and managed code.

·The unmanaged code is responsible for loading the CLR into a process and converting the program into managed code.

·The managed portion of the host is responsible for creating and managing the application domains.

There are mainly 2 reasons for hosts to have managed code and unmanaged code. The primary reason is a performance issue. There is a performance associated with calling a managed code from unmanaged code or vice versa. Hence, it is a better to call the unmanaged code and then go ahead with managed code (instead of transitioning from unmanaged host code to managed user code). It is also easy to implement/manage.

These are some of the hosts:

· ASP.NET

· Internet Explorer

· Shell Executables

· SQL Server 2005

Unmanaged Portion of CLR Hosts
Let us discuss more about the unmanaged code portion of the hosts before we go into the managed portion of code. All hosts must start with an unmanaged stub. The .NET Framework provides a set of unmanaged API's the host can use to get the CLR running.

As discussed above, the unmanaged portion of CLR hosts is responsible for loading the CLR into the process. Hosts use the CorBingToRunTimeEx API to load the CLR into the process. The CorBingToRunTimeEx API takes four parameters for loading the CLR. Let us discuss each parameter in detail. The code shown below is the unmanaged API CorBindToRuntimeHost.

Listing 1

HRESULT CorBindToRuntimeHost (
[in] LPCWSTR pwszVersion,
[in] LPCWSTR pwszBuildFlavor,
[in] LPCWSTR pwszHostConfigFile,
[in] VOID* pReserved,
[in] DWORD startupFlags,
[in] REFCLSID rclsid,
[in] REFIID riid,
[out] LPVOID FAR *ppv
);· Version - As shown in Listing 1, the pwszVersion is the parameter that determines which version of Common Language Runtime is to be loaded.

· Server versus workstation - As shown in Listing 1, pwszBuildFlavor specifies whether to load the server or the workstation build of the Common Language Runtime.

· Concurrent GC - StartupFlags specifies a set a predifined flags that control garbage collection.

1. STARTUP_CONCURRENT_GC - Specifies that concurrent garbage collection should be used.

· Loader optimization - Controls whether assemblies are loaded domain-neutrally. A domain neutral assembly is an assembly that can be shared by different application domains.

1. STARTUP_LOADER_OPTIMIZATION_SINGLE_DOMAIN - No assemblies are loaded as domain-neutral. [Except mscorlib] This setting is called single domain because it is commonly used when the host is running only a single application in the process.

2. STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN - All assemblies are loaded as domain-neutral.

3. STARTUP_LOADER_OPTIMIZATION_MULTI_DOMAIN_HOST All strong-named assemblies are loaded as domain-neutral.

Managed Portion of CLR Hosts
Now, the unmanaged portion of CLR host has loaded the CLR into the process. A default domain is created automatically by the CLR after it is loaded into the process. This default domain will be unloaded only after the process shuts down. This is the reason that most hosts do not run user code in the default domain as it cannot be shut down independently of the process. The ICorRuntimeHost is the interface that exposes some methods for creating application domains and unloading the same. Let us discuss some of the important methods of ICorRuntimeHost in detail. This will help us to understand ICorRunimeHost in a better manner.



Method Name
Description

CreateDomain
Creates an application domain. Gets an interface pointer of type System._AppDomain. Takes a friendly name of the Application domain.

CreateDomainEx
Creates an application domain. This method extends the functionality of the CreateDomain method by allowing the caller to pass the instance of IAppDomainSetup. IAppDomainSetup provides properties that allow the host to configure an AppDomain before calling ICorRuntimeHost::CreateDomainEx to create it. It has properties like ApplicationBase, Application Name, LicenseFile, etc.

Start
Starts the common language runtime.

Stop
Unloads the common language runtime from the current process.

UnloadDomain
Unloads the application domain represented by pAppDomain from the current process. Takes the reference of the application domain as the parameter.

EnumDomains
Returns an enumerator for the domains in the current process.

CurrentDomain
Returns an interface pointer to the AppDomain running on the current thread.

NextDomain
Returns an interface pointer to the next domain in the enumeration. Takes the EnumDomains as the parameter.

GetDefaultDomain
Returns an interface pointer of type _AppDomain, representing the default domain for the current process.


ICLRRunTimeHost is the interface developed for the CLR version 2.0. This interface is the superseded interface of ICorRuntimeHost. This interface has a new method called as SetHostControl. SetHostControl must be called before the common language runtime is initialized, that is, before a call to the Start method. It is always recommended to call SetHostControl immediately after a call to CorBindToRuntimeEx [Unmanaged API].

Creating Application Domains and Executing User code
The host can create application domains to run user code with security, isolation and unloading. It is not a better idea to run user code in the default domain. Let us list down the reasons for the same:

· A default domain cannot be unloaded until the process exists

· Security Isolation

Now that the host has created an application domain, we can execute user code in the domain. All code that is run in the CLR must be part of an assembly. An assembly is the deployment unit for types and resources and is the primary unit of execution in the CLR. The manner in which assemblies are loaded for execution depends largely on the host's specific scenario.

In general, there are two options:

· The first option is to load precompiled assemblies from a disk.

· The second option is to create assemblies on the fly using the API's in the System.Reflection.Emit namespace.

The code shown in Listing 2 is for creating an ApplicationDomain and executing an assembly into it. The code is written in C#. The Assembly that is loaded is an exe file.

Listing 2

ObjAppDomain = AppDomain.CreateDomain("My Application 1");
ObjAppDomain.ExecuteAssembly(@"C:\APPDOMAIN_Test.exe");The code shown below is for unloading the Application domain from the memory.

Listing 3

AppDomain.Unload(ObjAppDomain);
Code Access Security and Application Domains
All the managed code is subject to code access security. It is granted a set of code access permissions that determines what resource types it can access and what types of privileged operations it can perform. The Microsoft .NET Framework security system uses evidence to authenticate code to grant permissions. Evidence is used by the .NET Framework security system to identify assemblies. Code access security policy uses evidence to help grant the right permissions to the right assembly. Evidences can be classified of 2 types. Location related evidences and Author related evidences. The location related evidences can have a URL the assembly is obtained from or a directory the assembly is obtained from.

Code access security policy is configured by administrators and it determines the permissions granted to the assemblies. There are four types of policies identified for code access security.

· Enterprise - Used to apply Enterprise wide policy.

· Machine - Used to apply machine level policy.

· User - Used to apply Per-user policy.

· Application domain-level policy - ASP.NET code access security process is an example of Application domain level policy.

Execution of an Assembly by loading it into Application Domains

An assembly is said to be domain-neutral when its code can be shared by all domains in the process. The runtime host decides whether to load assemblies as domain-neutral when it loads the runtime into a process.

There are three options for loading domain-neutral assemblies:

Load no assemblies as domain-neutral, except Mscorlib, which is always loaded domain-neutral. This setting is called single domain because it is commonly used when the host is running only a single application in the process.

Load all assemblies as domain-neutral. Use this setting when there are multiple application domains in the process, all of which run the same code.

Load strong-named assemblies as domain-neutral. Use this setting when running more than one application in the same process.

In case of loading assemblies as domain-neutral, memory use and performance are at stake. The performance of a domain-neutral assembly is slower if that assembly contains static data or static methods that are accessed frequently. Access to static data or methods is slower because of the need to isolate applications. Each application domain that accesses the assembly must have a separate copy of the static data or method to prevent references to objects in static variables from crossing domain boundaries. As a result, the runtime contains additional logic to direct a caller to the appropriate copy of the static data or method. This extra logic slows down the call.

An assembly is not shared between domains when it is granted a different set of permissions in each domain. This can occur if the runtime host sets an application domain-level security policy. Assemblies should not be loaded as domain-neutral if the set of permissions granted to the assembly is to be different in each domain.

Conclusion
The CLR is the foundation on which the Microsoft .NET has been built. The CLR will be loaded into the memory by the host. A host can be an ISAPI filter, internet explorer or a Database engine. This is based on the type of the application. Hosts call the CorBindToRuntimeEx API to load the CLR into a process. There are four values a host can set when calling CorBindToRuntimeEx. These settings control which CLR gets loaded and how basic functions like garbage collection and class loading will behave in the process. The four settings are: version, server versus workstation, concurrent GC, and loader optimization. This will be he unmanaged portion of the host.

In order to begin running managed code, a host must obtain a pointer to an application domain. In many cases, this is the default domain within the process, but the host can also create additional domains as well. The GetConfiguration method on ICorRuntimeHost provides access to an interface called ICorConfiguration that can be used to configure specific aspects of the CLR that will be loaded into the process, or to register for additional events.


References