Basic Oops

41
Basic .NET, ASP.NET, OOPS and SQL Server Interview questions and answers. What is IL code, CLR,CTS,GAC,GC?> CLI - Common Language Infrastructure. Microsoft has a piece of shared source, its the public implementation of ECMA Common Language Infrastructure. This shared code is code-named "Rotor". It has around 3 million lines of code. Those who are interesed in development of a language that targets the .NET Framework, may extensively make use of this CLI. CIL- Stands for Common Intermediate Language. Its actually a low level human readable language implementation of CLI. All .NET-aware languages compile the source oode to an intermediate language called Common Intermediate Language using the language specific compiler. It is also possible to build .NET assemblies direclty using CIL using the ilasm.exe compiler. This compiler is shipped along with the .NET Framework 2.0 SDK. CIL is the only language that allows access to each aspect of the CTS. CIL is the definition of the fundamentals of the .NET framework. CTS - stands for Common Type Specification. It is at the core of .NET Framework's cross-language integration, type safety, and high-performance code execution. It defines a common set of types that can be used with many different language syntaxes. Each language (C#, VB.NET, Managed C++, and so on) is free to define any syntax it wishes, but if that language is built on the CLR, it will use at least some of the types defined by the CTS. Metadata - is code that describes the compiled IL. A .NET language compiler will generate the metadata and store this in the assembly containing the CIL. Metadata describes all class members and classes that are defined in the assembly, and the classes and class members that the current assembly will call from another assembly. When the CLR executes CIL it will check to make sure that the metadata of the called method is the same as the metadata that is stored in the calling method. This ensures that a method can only be called with exactly the correct number of parameters and exactly the correct parameter

Transcript of Basic Oops

Page 1: Basic Oops

Basic .NET, ASP.NET, OOPS and SQL Server Interview questions and answers.

What is IL code, CLR,CTS,GAC,GC?>

CLI - Common Language Infrastructure. Microsoft has a piece of shared source, its the public implementation of ECMA Common Language Infrastructure. This shared code is code-named "Rotor". It has around 3 million lines of code. Those who are interesed in development of a language that targets the .NET Framework, may extensively make use of this CLI.

CIL- Stands for Common Intermediate Language. Its actually a low level human readable language implementation of CLI. All .NET-aware languages compile the source oode to an intermediate language called Common Intermediate Language using the language specific compiler. It is also possible to build .NET assemblies direclty using CIL using the ilasm.exe compiler. This compiler is shipped along with the .NET Framework 2.0 SDK. CIL is the only language that allows access to each aspect of the CTS. CIL is the definition of the fundamentals of the .NET framework.

CTS - stands for Common Type Specification. It is at the core of .NET Framework's cross-language integration, type safety, and high-performance code execution. It defines a common set of types that can be used with many different language syntaxes. Each language (C#, VB.NET, Managed C++, and so on) is free to define any syntax it wishes, but if that language is built on the CLR, it will use at least some of the types defined by the CTS.

Metadata - is code that describes the compiled IL. A .NET language compiler will generate the metadata and store this in the assembly containing the CIL. Metadata describes all class members and classes that are defined in the assembly, and the classes and class members that the current assembly will call from another assembly. When the CLR executes CIL it will check to make sure that the metadata of the called method is the same as the metadata that is stored in the calling method. This ensures that a method can only be called with exactly the correct number of parameters and exactly the correct parameter types.

CLS - Common Language Specification. A type that is CLS compliant, may be used across any .NET language. CLS is a set of language rules that defines language standards for a .NET language and types declared in it.

IL - Intermediate Language, is the compiled form of the .NET language source code. When .NET source code is compiled by the language specific compiler (say we compile C# code using csc.exe), it is compiled to a .NET binary, which is platform independent, and is called Intermediate Language code.

VES - Virtual Execution System. The Virtual Execution System(VES) provides an environment for executing managed code. It provides direct support for a set of built-in data types, defines a hypothetical machine with an associated machine model and state, a set of control flow constructs, and an exception handling model.To a large extent, the purpose of the VES is to provide the support required to execute the Common Intermediate Language instruction set. 

Page 2: Basic Oops

What is a IL?

(IL)Intermediate Language is also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). All .NET source code is compiled to IL. This 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.

What is a CLR?

Full form of CLR is Common Language Runtime and it forms the heart of the .NET framework.All Languages have runtime and its the responsibility of the runtime to take care of the code execution of the program. For example VC++ has MSCRT40.DLL,VB6 has MSVBVM60.DLL, Java has Java Virtual Machine etc. Similarly .NET has CLR. Following are the responsibilities of CLR:

Garbage Collection :- CLR automatically manages memory thus eliminatingmemory leaks. When objects are not referred GC automatically releases those memories thus providing efficient memory management.

Code Access Security :- CAS grants rights to program depending on the security configuration of the machine. Example the program has rights to edit or create a new file but the security configuration of machine does not allow the program to delete a file. CAS will take care that the code runs under the environment of machines security configuration.

Code Verification :- This ensures proper code execution and type safety while the code runs. It prevents the source code to perform illegal operation such as accessing invalid memory locations etc.

IL( Intermediate language )-to-native translators and optimizer’s :- CLR uses JIT and compiles the IL code to machine code and then executes. CLR also determines depending on platform what is optimized way of running the IL code.

What is a CTS?

In order that two language communicate smoothly, CLR has CTS (Common Type System).Example in VB you have “Integer” and in C++ you have “long” these datatypes are not compatible so the interfacing between them is very complicated. In order to able that two different languages can communicate Microsoft introduced Common Type System. So “Integer” datatype in VB6 and “int” datatype in C++ will convert it to System.int32 which is datatype of CTS. CLS which is covered in the coming question is subset of CTS.

Note: If you have undergone COM programming period interfacing VB6 application with VC++ application was a real pain as the datatype of both languages did not have a common ground where they can come and interface, by having CTS interfacing is smooth.

What is a CLS(Common Language Specification)?

This is a subset of the CTS which all .NET languages are expected to support. Microsoft has defined CLS which are nothing but guidelines that language to follow so that it can communicate with other .NET languages in a seamless manner.

Page 3: Basic Oops

What is a Managed Code?

Managed code runs inside the environment of CLR i.e. .NET runtime. In short all IL are managed code. But if you are using some third party software example VB6 or VC++ component they are unmanaged code as .NET runtime (CLR) does not have control over the source code execution of the language.

What is a Assembly?

Assembly is unit of deployment like EXE or a DLL. An assembly consists of one or more files (dlls, exe’s, 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 assembly is completely self-describing.An assembly contains metadata information, which is used by the CLR for everything from type checking and security to actually invoking the components  methods. As all information is in the assembly itself, it is independent of registry. This is the basic advantage as compared to COM where the version was stored in registry.

Multiple versions can be deployed side by side in different folders. These different versions can execute at the same time without interfering with each other. Assemblies can be private or shared. For private assembly deployment, the assembly is copied to the same directory as the client program that references it. No registration is needed, and no fancy installation program is required.When the component is removed, no registry cleanup is needed, and no uninstall program is required. Just delete it from the hard drive.

In shared assembly deployment, an assembly is installed in the Global Assembly Cache (or GAC). The GAC contains shared assemblies that are globally accessible to all .NET applications on the machine.

What is Manifest?

Assembly metadata is stored in Manifest. Manifest contains all the metadata needed to do the following things (See Figure Manifest View for more details):

Version of assembly Security identity

Scope of the assembly

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 stand-alone PE file that contains only assembly manifest information.

Where is version information stored of an assembly?

Page 4: Basic Oops

Version information is stored in assembly in manifest.

Is versioning applicable to private assemblies?

Versioning concept is only applicable to global assembly cache (GAC) as private assembly lie in their individual folders.

What is GAC ?

GAC is used in the following situations :- If the application has to be shared among several application. If the assembly has some special security requirements like only administratorscan

remove the assembly. If the assembly is private then a simple delete ofassembly the assembly file will remove the assembly.

Note :- Registering .NET assembly in GAC can lead to the old problem of DLL hell,

where COM version was stored in central registry. So GAC should be used when absolutely

necessary.

What is the concept of strong names ?

Strong name is similar to GUID(It is supposed to be unique in space and time) in COM

components.Strong Name is only needed when we need to deploy assembly in GAC. Strong

Names helps GAC to differentiate between two versions. Strong names use public key

cryptography (PKC) to ensure that no one can spoof it.PKC use public key and private key

concept.

How can we do Assembly versioning?

Assembly Versioning

All versioning of assemblies that use the common language runtime is done at the assembly level. The specific version of an assembly and the versions of dependent assemblies are recorded in the assembly's manifest. The default version policy for the runtime is that applications run only with the versions they were built and tested with, unless overridden by explicit version policy in configuration files (the application configuration file, the publisher policy file, and the computer's administrator configuration file).

Note   Versioning is done only on assemblies with strong names.

The runtime performs several steps to resolve an assembly binding request:

Page 5: Basic Oops

1. Checks the original assembly reference to determine the version of the assembly to be bound.

2. Checks for all applicable configuration files to apply version policy.

3. Determines the correct assembly from the original assembly reference and any redirection specified in the configuration files, and determines the version that should be bound to the calling assembly.

4. Checks the global assembly cache, codebases specified in configuration files, and then checks the application's directory and subdirectories using the probing rules explained in How the Runtime Locates Assemblies.

The following illustration shows these steps.

Resolving an assembly binding request

For more information about configuring applications, see Configuration Files. For more information about binding policy, see How the Runtime Locates Assemblies.

Version Information

Each assembly has two distinct ways of expressing version information:

The assembly's version number, which, together with the assembly name and culture information, is part of the assembly's identity. This number is used by the runtime to enforce version policy and plays a key part in the type resolution process at run time.

An informational version, which is a string that represents additional version information included for informational purposes only.

Page 6: Basic Oops

Assembly Version Number

Each assembly has a version number as part of its identity. As such, two assemblies that differ by version number are considered by the runtime to be completely different assemblies. This version number is physically represented as a four-part string with the following format:

<major version>.<minor version>.<build number>.<revision>

For example, version 1.5.1254.0 indicates 1 as the major version, 5 as the minor version, 1254 as the build number, and 0 as the revision number.

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.

When an assembly is built, the development tool records dependency information for each assembly that is referenced in the assembly manifest. The runtime uses these version numbers, in conjunction with configuration information set by an administrator, an application, or a publisher, to load the proper version of a referenced assembly.

The runtime distinguishes between regular and strong-named assemblies for the purposes of versioning. Version checking only occurs with strong-named assemblies.

For information about specifying version binding policies, see Configuration Files. For information about how the runtime uses version information to find a particular assembly, see How the Runtime Locates Assemblies.

Assembly Informational Version

The informational version is a string that attaches additional version information to an assembly for informational purposes only; this information is not used at run time. The text-based informational version corresponds to the product's marketing literature, packaging, or product name and is not used by the runtime. For example, an informational version could be "Common Language Runtime version 1.0" or "NET Control SP 2".

can you explain how ASP.NET application life cycle and page life cycle events fire?

Introduction  

In this article we will try to understand what are the different events which takes place right from the time the user sends a request, until the time request is rendered on the browser. So we will first try to understand the two broader steps of an ASP.NET request and then we will move in to different events emitted from ‘HttpHandler’, ‘HttpModule’ and ASP.NET page

Page 7: Basic Oops

object. As we move in this event journey we will try to understand what kind of logic should go in each every of these events.

This is a small Ebook for all my .NET friends which covers topics like WCF,WPF,WWF,Ajax,Core .NET,SQL etc you can download the same from http://tinyurl.com/4nvp9t  or else you can catch me on my daily free training @ http://tinyurl.com/y4mbsn6   

The Two step process  

From 30,000 feet level ASP.NET request processing is a 2 step process as shown below. User sends a request to the IIS:-• ASP.NET creates an environment which can process the request. In other words it creates the application object, request, response and context objects to process the request.• Once the environment is created the request is processed through series of events which is processed by using modules, handlers and page objects. To keep it short lets name this step as MHPM (Module, handler, page and Module event), we will come to details later. 

In the coming sections we will understand both these main steps in more details. 

Creation of ASP.NET environment  

Step 1:- The user sends a request to IIS. IIS first checks which ISAPI extension can serve this request. Depending on file extension the request is processed. For instance if the page is an ‘.ASPX page’ then it will be passed to ‘aspnet_isapi.dll’ for processing.

Step 2:- If this the first request to the website then a class called as ‘ApplicationManager’ creates an application domain where the website can run. As we all know application domain creates isolation between two web applications hosted on the same IIS. So in case there is

Page 8: Basic Oops

issue in one app domain it does not affect the other app domain.

Step 3:- The newly created application domain creates hosting environment i.e. the ‘HttpRuntime’ object. Once the hosting environment is created necessary core ASP.NET objects like ‘HttpContext’ , ‘HttpRequest’ and ‘HttpResponse’ objects are created.

Step 4:- Once all the core ASP.NET objects are created ‘HttpApplication’ object is created to serve the request. In case you have a ‘global.asax’ file in your system then object of the ‘global.asax’ file will be created. Please note ‘global.asax’ file inherits from ‘HttpApplication’ class.Note: The first time an ASP.NET page is attached to an application, a new instance of ‘HttpApplication’ is created. Said and done to maximize performance, ‘HttpApplication’ instances might be reused for multiple requests.

Step 5:- The ‘HttpApplication’ object is then assigned to the core ASP.NET objects to process the page.

Step 6:- ‘HttpApplication’ then starts processing the request by http module events , handlers and page events. It fires the MHPM event for request processing.Note: - For more details http://msdn.microsoft.com/en-us/library/ms178473.aspx 

Page 9: Basic Oops

Below image explains how the internal object model looks like for an ASP.NET request. At the top level is the ASP.NET runtime which has creates an ‘Appdomain’ which in turn has ‘HttpRuntime’ with ‘request’, ‘response’ and ‘context’ objects.

Page 10: Basic Oops

Process request using MHPM events fired  

Once ‘HttpApplication’ is created it starts processing request it goes through 3 different sections ‘HttpModule’ , ‘Page’ and ‘HttpHandler’. As it moves through these sections it invokes different events which the developer can extend and add customize logic to the same.Before we move ahead lets understand what are ‘HttpModule’ and ‘HttpHandlers’. They help us to inject custom logic before and after the ASP.NET page is processed. The main differences between both of them are:- • If you want to inject logic based in file extensions like ‘.ASPX’ , ‘.HTML’ then you use ‘HttpHandler’. In other words ‘HttpHandler’ is an extension based processor. 

Page 11: Basic Oops

• If you want to inject logic in the events of ASP.NET pipleline then you use ‘HttpModule’. ASP.NET . In other word ‘HttpModule’ is an event based processor.

You can read more about the differences from http://computerauthor.blogspot.com/2009/09/two-interceptors-httpmodule-and.html  Below is the logical flow of how the request is processed. There are 4 important steps MHPM as explained below :-

Step 1(M ? HttpModule):- Client request processing starts. Before the ASP.NET engine goes and creates the ASP.NET ‘HttpModule’ emits events which can be used to inject

Page 12: Basic Oops

customized logic. There are 6 important events which you can utilize before your page object is created ‘BeginRequest’,’AuthenticateRequest’,’AuthorizeRequest’,’ResolveRequestCache’,’AcquireRequestState’ and ‘PreRequestHandlerExecute’.

Step 2 (H ? ‘HttpHandler’ ) :- Once the above 6 events are fired , ASP.NET engine will invoke ‘ProcessRequest’ event if you have implemented ‘HttpHandler’ in your project.

Step 3 (P – ASP.NET page):- Once the ‘HttpHandler’ logic executes the ASP.NET page object is created. While the ASP.NET page object is created many events are fired which can help us to write our custom logic inside those page events. There are 6 important events which provides us placeholder to write logic inside ASP.NET pages ‘Init’ , ‘Load’ , ‘validate’ , ‘event’ , ‘render’ and ‘unload’. You can remember the word ‘SILVER’ to remember the events S – Start ( does not signify anything as such just forms the word ) , I – (Init) , L ( Load) , V ( Validate) , E ( Event) and R ( Render).

Step4 (M ? HttpModule):- Once the page object is executed and unloaded from memory ‘HttpModule’ provides post page execution events which can be used to inject custom post-processing logic. There are 4 important post-processing events ‘PostRequestHandlerExecute’, ‘ReleaserequestState’, ‘UpdateRequestCache’ and ‘EndRequest’.Below figure shows the same in a pictorial format. 

Page 13: Basic Oops

In What event we should do what?  

The million dollar question is in which events we should do what? . Below is the table which shows in which event what kind of logic or code can go. 

Section Event Description

HttpModule BeginRequest This event signals a new request; it is guaranteed to be raised on each request.

HttpModule AuthenticateRequest This event signals that ASP.NET runtime is ready to authenticate the user. Any authentication code can be injected here.

Page 14: Basic Oops

HttpModule AuthorizeRequest This event signals that ASP.NET runtime is ready to authorize the user. Any authorization code can be injected here.

HttpModule ResolveRequestCache

In ASP.NET we normally use outputcache directive to do caching. In this event ASP.NET runtime determines if the page can be served from the cache rather than loading the patch from scratch. Any caching specific activity can be injected here.

HttpModule AcquireRequestState This event signals that ASP.NET runtime is ready to acquire session variables. Any processing you would like to do on session variables.

HttpModule PreRequestHandlerExecute

This event is raised just prior to handling control to the HttpHandler. Before you want the control to be handed over to the handler any pre-processing you would like to do.

HttpHandler ProcessRequest Httphandler logic is executed. In this section we will write logic which needs to be executed as per page extensions.

Page Init

This event happens in the ASP.NET page and can be used for :-

    Creating controls dynamically, in case you have controls to be created on runtime.

    Any setting initialization.

     Master pages and them settings.

In this section we do not have access to viewstate , postedvalues and neither the controls are initialized.

 

Page Load In this section the ASP.NET controls are fully loaded and you write UI manipulation logic or any other logic over here.

Page Validate If you have valuators on your page, you would like to check the same here.

Render It’s now time to send the output to the browser. If you would like to make some changes to the final HTML which is going out to the browser you can enter your HTML logic

Page 15: Basic Oops

here.

Page Unload Page object is unloaded from the memory.

HttpModule PostRequestHandlerExecute Any logic you would like to inject after the handlers are executed.

HttpModule ReleaserequestState If you would like to save update some state variables like session variables.

HttpModule UpdateRequestCache Before you end if you want to update your cache.

HttpModule EndRequest This is the last stage before your output is sent to the client browser.

 

A sample code for demonstration  

With this article we have attached a sample code which shows how the events actually fire. In this code we have created a ‘HttpModule’ and ‘Httphandler’ in this project and we have displayed a simple response write in all events , below is how the output looks like.Below is the class for ‘HttpModule’ which tracks all event s and adds it to a global collection. 

public class clsHttpModule : IHttpModule{......

void OnUpdateRequestCache(object sender, EventArgs a)

{objArrayList.Add("httpModule:OnUpdateRequestCache");}void OnReleaseRequestState(object sender, EventArgs a){objArrayList.Add("httpModule:OnReleaseRequestState");}void OnPostRequestHandlerExecute(object sender, EventArgs a){objArrayList.Add("httpModule:OnPostRequestHandlerExecute");}void OnPreRequestHandlerExecute(object sender, EventArgs a){objArrayList.Add("httpModule:OnPreRequestHandlerExecute");}void OnAcquireRequestState(object sender, EventArgs a){objArrayList.Add("httpModule:OnAcquireRequestState");

Page 16: Basic Oops

}void OnResolveRequestCache(object sender, EventArgs a){objArrayList.Add("httpModule:OnResolveRequestCache");}void OnAuthorization(object sender, EventArgs a){objArrayList.Add("httpModule:OnAuthorization");}void OnAuthentication(object sender, EventArgs a){

objArrayList.Add("httpModule:AuthenticateRequest");}void OnBeginrequest(object sender, EventArgs a){

objArrayList.Add("httpModule:BeginRequest");}void OnEndRequest(object sender, EventArgs a){objArrayList.Add("httpModule:EndRequest");objArrayList.Add("<hr>");foreach (string str in objArrayList){httpApp.Context.Response.Write(str + "<br>") ;}} }

 

Below is the code snippet for ‘HttpHandler’ which tracks ‘ProcessRequest’ event. 

public class clsHttpHandler : IHttpHandler{

public void ProcessRequest(HttpContext context)

{clsHttpModule.objArrayList.Add("HttpHandler:ProcessRequest");context.Response.Redirect("Default.aspx");}}

 

We are also tracking all the events from the ASP.NET page. 

public partial class _Default : System.Web.UI.Page {

Page 17: Basic Oops

protected void Page_init(object sender, EventArgs e){

clsHttpModule.objArrayList.Add("Page:Init");}protected void Page_Load(object sender, EventArgs e){clsHttpModule.objArrayList.Add("Page:Load");}public override void Validate() {clsHttpModule.objArrayList.Add("Page:Validate");}protected void Button1_Click(object sender, EventArgs e){clsHttpModule.objArrayList.Add("Page:Event");}protected override void Render(HtmlTextWriter output) {clsHttpModule.objArrayList.Add("Page:Render");base.Render(output);}protected void Page_Unload(object sender, EventArgs e){clsHttpModule.objArrayList.Add("Page:UnLoad");}}

 

Below is how the display looks like with all events as per the sequence discussed in the previous section. 

Page 18: Basic Oops

Zooming ASP.NET page events  

In the above section we have seen the overall flow of events for an ASP.NET page request. One of the most important section is the ASP.NET page, we have not discussed the same in detail. So let’s take some luxury to describe the ASP.NET page events in more detail in this section.Any ASP.NET page has 2 parts one is the page which is displayed on the browser which has HTML tags , hidden values in form of viewstate and data on the HTML inputs. When the page is posted these HTML tags are created in to ASP.NET controls with viewstate and form data tied up together on the server. Once you get these full server controls on the behind code you can execute and write your own login on the same and render the page back to the browser. 

Page 19: Basic Oops

Now between these HTML controls coming live on the server as ASP.NET controls, the ASP.NET page emits out lot of events which can be consumed to inject logic. Depending on what task / logic you want to perform we need to put these logics appropriately in those events.Note: - Most of the developers directly use the ‘page_load’ method for everything, which is not a good thought. So it’s either populating the controls, setting view state, applying themes etc everything happens on the page load. So if we can put logic in proper events as per the nature of the logic that would really make your code clean. 

Seq Events Controls Initialized

View state

Available

Form dataAvailable

What Logic can be written here? 

1 Init No No No

Note: - You can access form data etc by using ASP.NET request objects but not by Server controls.Creating controls dynamically, in case you have controls to be created on runtime. Any setting initialization.Master pages and them settings.In this section we do not have access to viewstate , posted values and neither the controls are initialized.

2 Load view state

Not guaranteed

Yes Not guaranteed

You can access view state and any synch logic where you want viewstate to be pushed to

Page 20: Basic Oops

behind code variables can be done here.

3 PostBackdata Not guaranteed

Yes Yes You can access form data. Any logic where you want the form data to be pushed to behind code variables can be done here.

4 Load Yes Yes Yes

This is the place where you will put any logic you want to operate on the controls. Like flourishing a combox box from the database , sorting data on a grid etc. In this event we get access to all controls , viewstate and their posted values.

5 Validate Yes Yes Yes If your page has validators or you want execute validation for your page this is the right place to the same.

6 Event Yes Yes Yes

If this is a post back by a button click or a dropdown change then the relative events will be fired. Any kind of logic which is related to that event can be executed here.

7 Pre-render Yes Yes Yes

If you want to make final changes to the UI objects like changing tree structure or property values, before these controls are saved in to view state.

8 Save view state

Yes Yes Yes Once all changes to server controls are done this event can be an opportunity to save control data in to view state.

9 Render Yes Yes Yes If you want to add some custom HTML to the output this is the place you can.

10 Unload Yes Yes Yes Any kind of clean up you would like to do here.

Page 21: Basic Oops

Can you define OOP and the 4 principles of OOP?

4.7. What is Encapsulation (or information hiding)?The encapsulation is the inclusion within a program object of all the resources need for the object to function - basically, the methods and the data. In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its

Page 22: Basic Oops

internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do.

In order to modularize/ define the functionality of a one class, that class can uses functions/ properties exposed by another class in many different ways. According to Object Oriented Programming there are several techniques, classes can use to link with each other and they are named association, aggregation, and composition.

There are several other ways that an encapsulation can be used, as an example we can take the usage of an interface. The interface can be used to hide the information of an implemented class.

Collapse

IStudent myStudent = new LocalStudent();IStudent myStudent = new ForeignStudent();

According to the sample above (let’s assume that LocalStudent and ForeignStudent are

implemented by the IStudent interface) we can see how LocalStudent and ForeignStudent are

hiding their, localize implementing information through the IStudent interface.

4.10. What is Abstraction and Generalization?Abstraction is an emphasis on the idea, qualities and properties rather than the particulars (a suppression of detail). The importance of abstraction is derived from its ability to hide irrelevant details and from the use of names to reference objects. Abstraction is essential in the construction of programs. It places the emphasis on what an object is or does rather than how it is represented or how it works. Thus, it is the primary means of managing complexity in large programs.

While abstraction reduces complexity by hiding irrelevant detail, generalization reduces complexity by replacing multiple entities which perform similar functions with a single construct. Generalization is the broadening of application to encompass a larger domain of objects of the same or different type. Programming languages provide generalization through variables, parameterization, generics and polymorphism. It places the emphasis on the similarities between objects. Thus, it helps to manage complexity by collecting individuals into groups and providing a representative which can be used to specify any individual of the group.

Abstraction and generalization are often used together. Abstracts are generalized through parameterization to provide greater utility. In parameterization, one or more parts of an entity are replaced with a name which is new to the entity. The name is used as a parameter. When

Page 23: Basic Oops

the parameterized abstract is invoked, it is invoked with a binding of the parameter to an argument.

4.11. What is an Abstract class?Abstract classes, which declared with the abstract keyword, cannot be instantiated. It can only be used as a super-class for other classes that extend the abstract class. Abstract class is the concept and implementation gets completed when it is being realized by a subclass. In addition to this a class can inherit only from one abstract class (but a class may implement many interfaces) and must override all its abstract methods/ properties and may override virtual methods/ properties.

Abstract classes are ideal when implementing frameworks. As an example, let’s study the abstract class named LoggerBase below. Please carefully read the comments as it will help you to understand the reasoning behind this code.

Collapse

public abstract class LoggerBase{ /// <summary> /// field is private, so it intend to use inside the class only /// </summary> private log4net.ILog logger = null;

/// <summary> /// protected, so it only visible for inherited class /// </summary> protected LoggerBase() { // The private object is created inside the constructor logger = log4net.LogManager.GetLogger(this.LogPrefix); // The additional initialization is done immediately after log4net.Config.DOMConfigurator.Configure(); }

/// <summary> /// When you define the property as abstract, /// it forces the inherited class to override the LogPrefix /// So, with the help of this technique the log can be made, /// inside the abstract class itself, irrespective of it origin. /// If you study carefully you will find a reason for not to have “set” method here. /// </summary> protected abstract System.Type LogPrefix { get; }

/// <summary> /// Simple log method, /// which is only visible for inherited classes /// </summary> /// <param name="message"></param> protected void LogError(string message) { if (this.logger.IsErrorEnabled) { this.logger.Error(message);

Page 24: Basic Oops

} }

/// <summary> /// Public properties which exposes to inherited class /// and all other classes that have access to inherited class /// </summary> public bool IsThisLogError { get { return this.logger.IsErrorEnabled; } }}The idea of having this class as an abstract is to define a framework for exception logging. This class will allow all subclass to gain access to a common exception logging module and will facilitate to easily replace the logging library. By the time you define the LoggerBase, you wouldn’t have an idea about other modules of the system. But you do have a concept in mind and that is, if a class is going to log an exception, they have to inherit the LoggerBase. In other word the LoggerBase provide a framework for exception logging.

Let’s try to understand each line of the above code.

Like any other class, an abstract class can contain fields, hence I used a private field named logger declare the ILog interface of the famous log4net library. This will allow the Loggerbase class to control, what to use, for logging, hence, will allow changing the source logger library easily.

The access modifier of the constructor of the LoggerBase is protected. The public constructor has no use when the class is of type abstract. The abstract classes are not allowed to instantiate the class. So I went for the protected constructor.

The abstract property named LogPrefix is an important one. It enforces and guarantees to have a value for LogPrefix (LogPrefix uses to obtain the detail of the source class, which the exception has occurred) for every subclass, before they invoke a method to log an error.

The method named LogError is protected, hence exposed to all subclasses. You are not allowed or rather you cannot make it public, as any class, without inheriting the LoggerBase cannot use it meaningfully.

Let’s find out why the property named IsThisLogError is public. It may be important/ useful for other associated classes of an inherited class to know whether the associated member logs its errors or not.

Apart from these you can also have virtual methods defined in an abstract class. The virtual method may have its default implementation, where a subclass can override it when required.

All and all, the important factor here is that all OOP concepts should be used carefully with reasons, you should be able to logically explain, why you make a property a public or a field a private or a class an abstract. Additionally, when architecting frameworks, the OOP

Page 25: Basic Oops

concepts can be used to forcefully guide the system to be developed in the way framework architect’s wanted it to be architected initially.

4.16. What is Inheritance?

Ability of a new class to be created, from an existing class by extending it, is called inheritance.

Collapse

public class Exception{}

public class IOException : Exception{}

According to the above example the new class (IOException), which is called the derived class or subclass, inherits the members of an existing class (Exception), which is called the base class or super-class. The class IOException can extend the functionality of the class Exception by adding new types and methods and by overriding existing ones.

Just like abstraction is closely related with generalization, the inheritance is closely related with specialization. It is important to discuss those two concepts together with generalization to better understand and to reduce the complexity.

One of the most important relationships among objects in the real world is specialization, which can be described as the “is-a” relationship. When we say that a dog is a mammal, we mean that the dog is a specialized kind of mammal. It has all the characteristics of any mammal (it bears live young, nurses with milk, has hair), but it specializes these characteristics to the familiar characteristics of canis domesticus. A cat is also a mammal. As such, we expect it to share certain characteristics with the dog that are generalized in Mammal, but to differ in those characteristics that are specialized in cats.

The specialization and generalization relationships are both reciprocal and hierarchical. Specialization is just the other side of the generalization coin: Mammal generalizes what is common between dogs and cats, and dogs and cats specialize mammals to their own specific subtypes.

Page 26: Basic Oops

Similarly, as an example you can say that both IOException and SecurityException are of type Exception. They have all characteristics and behaviors of an Exception, That mean the IOException is a specialized kind of Exception. A SecurityException is also an Exception. As such, we expect it to share certain characteristic with IOException that are generalized in Exception, but to differ in those characteristics that are specialized in SecurityExceptions. In other words, Exception generalizes the shared characteristics of both IOException and SecurityException, while IOException and SecurityException specialize with their characteristics and behaviors.

In OOP, the specialization relationship is implemented using the principle called inheritance. This is the most common and most natural and widely accepted way of implement this relationship.

4.17. What is Polymorphisms?Polymorphisms is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.

At times, I used to think that understanding Object Oriented Programming concepts have made it difficult since they have grouped under four main concepts, while each concept is closely related with one another. Hence one has to be extremely careful to correctly understand each concept separately, while understanding the way each related with other concepts.

What are Classes and Objects?

4.5. What is a Class?

A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.

public class Student{}According to the sample given below we can say that the student object, named objectStudent, has created out of the Student class.

Student objectStudent = new Student();

Page 27: Basic Oops

In real world, you'll often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles.

In the software world, though you may not have realized it, you have already used classes. For example, the TextBox control, you always used, is made out of the TextBox class, which defines its appearance and capabilities. Each time you drag a TextBox control, you are actually creating a new instance of the TextBox class.

What is Inheritance?

What is Polymorphism, overloading, overriding and virtual?

Can you explain encapsulation and abstraction?

What is an abstract class?

Define Interface & What is the diff. between abstract & interface?

What problem does Delegate Solve ?

What is a Multicast delegate ?

What are events and what's the difference between delegates and events?

Page 28: Basic Oops

How can we make Asynchronous method calls using delegates ?

What is a stack, Heap, Value types and Reference types ?

What is boxing and unboxing ?

Can you explain ASP.NET application and Page life cycle ?

What is Authentication, Authorization, Principal & Identity objects?

How can we do Inproc and outProc session management ?

How can we windows , forms and passport authentication and authorization in ASP.NET ?

In a parent child relationship which constructor fires first ?

WCF,WPF,Silverlight ,LINQ, Azure and EF 4.0 interview question and answers

What is SOA, Services and Messages ? What is the difference between Service and Component? What are basic steps to create a WCF service ? What are endpoints, address, contracts and bindings? What are various ways of hosting WCF service? What is the difference of hosting a WCF service on IIS and

Self hosting?

Page 29: Basic Oops

What is the difference between BasicHttpBinding and WsHttpBinding?

How can we do debugging and tracing in WCF? Can you explain transactions in WCF (theory)? How can we self host WCF service ? What are the different ways of implementing WCF

Security? How can we implement SSL security on WCF(Transport

Security)? How can we implement transport security plus message

security in WCF ? How can we do WCF instancing ? How Can we do WCF Concurency and throttling? Can you explain the architecture of Silverlight ? What are the basic things needed to make a silverlight

application ? How can we do transformations in SilverLight ? Can you explain animation fundamentals in SilverLight? What are the different layout methodologies in

SilverLight? Can you explain one way , two way and one time

bindings? How can we consume WCF service in SilverLight? How can we connect databases using SilverLight? What is LINQ and can you explain same with example? Can you explain a simple example of LINQ to SQL? How can we define relationships using LINQ to SQL? How can we optimize LINQ relationships queries using

‘DataLoadOptions’? Can we see a simple example of how we can do CRUD

using LINQ to SQL? How can we call a stored procedure using LINQ? What is the need of WPF when we had GDI, GDI+ and

DirectX? Can you explain how we can make a simple WPF

application?

Page 30: Basic Oops

Can you explain the three rendering modes i.e. Tier 0 , Tier 1 and Tier 2?

Can you explain the Architecture of WPF? What is Azure? Can you explain Azure Costing? Can we see a simple Azure sample program? What are the different steps to create a simple Worker

application? Can we understand Blobs in steps, Tables & Queues ? Can we see a simple example for Azure tables? What is Package and One click deploy(Deployment Part -

1) ? What is Web.config transformation (Deployment Part-2)? What is MEF and how can we implement the same? How is MEF different from DIIOC? Can you show us a simple implementation of MEF in

Silverlight ?Design pattern, Estimation, VSTS, Project management interview questions and answers 

Design Pattern Training / Interview Questions and Answers Introduction Factory Design Pattern Abstract Factory Design Pattern Builder Design Pattern Prototype Design Pattern Singleton Design Pattern Adapter Design Pattern Bridge Design Pattern Composite Design Pattern Decorator Design Pattern Facade Design Pattern Flyweight Design Pattern Proxy Design Pattern Mediator Design Pattern Memento Design Pattern Interpreter Design Pattern

Page 31: Basic Oops

Iterator Design Pattern COR Design Pattern Command Design Pattren State Design Pattern Strategy Design Pattern Observer Design Pattern Template Design Pattern Visitor Design Pattern Dependency IOC Design pattern MVC , MVP , DI IOC and MVVM Training / Interview

Questions and Answers

UML Training / Interview Questions and Answers Introduction Use Case Diagrams Class Digrams Object Diagrams Sequence Digrams Collaboration Diagrams Activity Diagram State chart Diagrams Component Diagrams Deployment Diagrams Stereo Types Diagrams Package Diagram and UML Project Flow.Function points Training / Interview Questions and Answers

Introduction Application Boundary EI Fundamentals EO Fundamentals EQ Fundamentals EIF Fundamentals ILF Fundamentals GSC Fundamentals

Page 32: Basic Oops

Productivity Factor Costing and a complete estimation of customer screen

using function points. FXCOP and Stylecop Training / Interview Questions and

Answers

VSTS Training / Interview Questions and Answers VSTS questions and answer videos What is Unit Testing & can we see an example of the

same? How can we write data driven test using NUNIT & VS Test? Can we see simple example of a unit test for database

operation? How can we do automated testing using Visual Studio

Test? How can we do Load Testing using VSTS test? Can you explain database unit testing? How can we do test coverage using VSTS system? How can we do manual Testing using VSTS? What is Ordered Test in VSTS test?

Enterprise Application Blocks Training Introduction Validation Application Block Logging Application Block Exception error Handling Data Application Block Caching Application Block Security Application Block Policy Injection Application Block and Unity Application Block

Page 33: Basic Oops

Complete .NET invoicing project end to end Introduction to .NET Projects Different levels of Programming Necessary Tools What should we learn ? The IIS Making UI using .net IDE Database, The SQL Server Connecting ASP.net with Database Loading the Data Grid Update and Delete Validations Issue with the Code Two Tier Architecture Three Tier Architecture Database Normalization Session and State Management Using Enterprise Application Block Aggregation and Composition Implementing Interfaces and Factory Inheritance relationship Abstract Class Implementation

Share point interview Training / Interview Questions and Answers videos

What is SharePoint, WSS and MOSS? How does WSS actually work? What is Site and SiteCollection? What is the use of SQL server in SharePoint & use of

Virtual path provider? What is Ghosting and UnGhosting in SharePoint? How can we create a site in SharePoint? How can we Customize a SharePoint Site?

Page 34: Basic Oops

What kind of readymade functional modules exists collaboration?

Can you display a simple Custom Page in SharePoint? How can we implement behind code ASPX pages in

SharePoint? What is the concept of features in SharePoint? I want a feature to be only displayed to admin? How do we debug SharePoint error’s? Why customized pages are parsed using no-compile

mode? Can you explain WSS model? How can we use custom controls in SharePoint? How can we display ASCX control in SharePoint pages? What are Web Parts? How can we deploy a simple Webpart in SharePoint? How can we achieve customization and personalization

using WebParts? How can we create custom editor for WebPart? SharePoint is about centralizing documents, how similar is

to the windows folder? What are custom fields and content types? Can you explain SharePoint Workflows? What is a three-state Workflow in SharePoint? How can we create sharepoint workflow using sharepoint

designer?

.NET best practices and SQL Server Training / Interview Questions and Answers

Basics :- Query plan, Logical operators and Logical reads Point 1 :- Unique keys improve table scan performance. Point 2 :- Choose Table scan for small & Seek scan for

large records Point 3 :- Use Covering index to reduce RID (Row

Identifier) lookup Point4:- Keep index size as small as possible.

Page 35: Basic Oops

Point5:- use numeric as compared to text data type. Point6:- use indexed view for aggregated SQL Queries Finding high memory consuming functions Improve garbage collector performance using

finalize/dispose pattern How to use performance counters to gather performance

data