Monday, 4 August 2014

ASP.Net FAQ Part-1

Can you explain the term concurrency?

Concurrency issues happen in multiuser environment when multiple people update the same data at the same time.

Below is the sequence of events how concurrency issues can happen:-
  • User A fetches data with value “X” and starts changing this value to “Y”.
  • User B also fetches the same “X” data and starts changing this value to “Z”.
  • Now User B first updates the data to database. In other words he changes the data to “Z”.
  • Now User A also sends the update to database. In other words he changes the data to “Y”.
Now User A thinks he has changed “X” to “Y” and User B thinks the current data is “Z”. Both of them are wrong and this leads to confusion termed as “Concurrency” problem.

How can we resolve concurrency issue?

Concurrency issue can be resolved by using optimistic or pessimistic locking.

What are the major differences between classic ADO and ADO.NET?

Following are some major differences between both:-
  • In ADO we have recordset and in ADO.NET we have dataset.
  • In recordset we can only have one table. If we want to accommodate more than one tables we need to do inner join and fill the recordset. Dataset can have multiple tables.
  • All data persist in XML as compared to classic ADO where data persisted in Binary format also
What’s difference between “Optimistic” and “Pessimistic” locking?

In optimistic locking there is no locking actually. It only checks if  the old values are changed, in case they are changed it means somebody has changed the data, so it raises exception.

In pessimistic locking you actually lock the record, depending on the type of lock no other process can make modifications to the record.

How many ways are there to implement optimistic locking in ADO.NET?

Following are the ways to implement optimistic locking using ADO.NET:-
  • When we call “Update” method of Data Adapter it handles locking internally. If the Dataset values are not matching with current data in Database, it raises concurrency exception error. We can easily trap this error using Try. Catch block and raise appropriate error message to the user.
  • Define a Date time stamp field in the table. When actually you are firing the UPDATE SQL statements, compare the current timestamp with one existing in the database. Below is a sample SQL which checks for timestamp before updating and any mismatch in timestamp it will not update the records. This I the best practice used by industries for locking.
Update table1 set field1=@test where Last Timestamp=@Current Timestamp
  • Check for original values stored in SQL SERVER and actual changed values. In stored procedure check before updating that the old data is same as the current Example in the below shown SQL before updating field1 we check that is the old field1 value same. If not then some one else has updated and necessary action has to be taken.
Update table1 set field1=@test where field1 = @oldfield1value

Locking can be handled at ADO.NET side or at SQL SERVER side i.e. in stored procedures. For more details of how to implementing locking in SQL SERVER read “What are different locks in SQL SERVER?” in SQL SERVER chapter.

How can do pessimistic locking?

Pessimistic locking is done by using transaction isolation levels like read committed, read uncommitted, repeatable read and serializable.

See following video on Dataset is a disconnect while datareader is connected: -


Referenced by:- Please do visit us at http://www.questpond.com for 600 .Net interview question with answer videos

What is LINQ and Entity framework?

LINQ is a uniform programming model for any kind of data access. It is also an OR mapper which helps us to expedite our business object creation process.

See following video on explaining LINQ: -


Entity Framework auto-generates code for the Model (middle layer), Data Access Layer, and mapping code, thus reducing a lot of development time.

ADO.NET entity is an ORM (object relational mapping) which creates a higher abstract object model over ADO.NET components. So rather than getting into dataset, datatables, command, and connection objects as shown in the below code, you work on higher level domain objects like customers, suppliers, etc.

In other words the complete middle tier development is expedited using entity framework.

What is an IL code?

It’s a CPU independent partially compiled code.

What is an Assembly?

Assembly is unit of deployment like EXE or a DLL.

What is a CLR?

CLR (Common language run time) is the heart of.NET framework and it does 4 primary important things:-
  • Garbage collection
  • CAS (Code Access security)
  • CV (Code verification)
  • IL to Native translation.
What is a garbage collector?

Garbage collector is a feature of CLR which cleans unused managed (it does not clean unmanaged objects) objects and reclaims memory. It’s a back ground thread which runs continuously and at specific intervals it checks if there are any unused objects whose memory can be claimed.

What is CTS?

In .NET there are lots of languages like C#, VB.NET, VF.NET etc.  There can be situations when we want code in one language to be called in other language. In order to ensure smooth communication between these languages the most important thing is that they should have a common type system. CTS (Common types system) ensures that data types defined in two different languages get compiled to a common data type.

So “Integer” data type in VB6 and “int” data type in C++ will be converted to System.int32, which is data type of CTS.

What is a CLS (Common Language Specification)?

CLS is a subset of CTS. CLS is a specification or set of rules or guidelines. When any programming language adheres to these set of rules it can be consumed by any .NET language.

For instance one of the rule which makes your application CLS non-compliant is when you declare your methods members with same name and with only case differences in C#. You can try this create a simple class in C# with same name with  only case differences and try to consume the same in VB.NET ,it will not work.

What is a Class and structure’s?

Structures are value types and classes are reference types..

When to use Structures and When to use classes?

You will use structures when: -

Point 1:- If you want to represent a custom value type. This custom value type is derived from primitive data types (int, double). Some of the example’s of custom types are co-ordinates (which have X, Y), complex numbers (which have real and imaginary components).  You can also term these things as value objects or technical objects. Technical objects do not represent real world objects like customer, supplier, invoice etc.

Point 2:- If you want to have low memory foot print. For instance let’s say you want to plot a graph. To plot a graph you need to have 100’s of objects created so that you can represent co-ordinates.  Now if you create a class and generate those 100’s of objects you end up putting lot of load on your garbage collector. If you create a “struct” , it’s a value type. So they get created and destroyed immediately. Thus putting less load on memory.
For all other scenarios use a class.
                                      

What are similarities between Class and structure?

Following are the similarities between classes and structures:-
  • Both can have constructors, methods, properties, fields, constants, enumerations, events, and event handlers.
  • Structures and classes can implement interface.
  • Both of them can have constructors with and without parameter.
  • Both can have delegates and events.
What is the difference between Class and structure’s?

Following are the key differences between them:-
  • Structures are value types and classes are reference types. So structures use stack and classes use heap.
  • Structures members cannot be declared as protected, but class members can be. You cannot do inheritance in structures.
  • Structures do not require constructors while classes require.
  • Objects created from classes are terminated using Garbage collector. Structures are not destroyed using GC.
What are Accessors and mutators in C#?

Look at the following example,

public class Customer
{
            publicint Age;
            .
            .
            .
}

Now in the client code we will do something like this.

Customer c=new Customer();
c.Age=55;

But do you realize one thing even we can do something like this,

c.Age=563;
OR
c.Age=-65;

This is not a valid statement logically but it’s valid syntactically. Our program will just execute perfectly fine.

One of the pillar of Object oriented principle called Encapsulation let us protect our data by creating a wrapper around our data, logic etc. by means of functions, classes etc. In short Encapsulation also let us protects our data.

Usually we will do something like this.

public class Customer
{
            privateint Age; // data is private
            .
            .
            .
            publicintGetAge() // Data is exposed to outside world via public method
            {
                        Return Age;
            }
            publicvoid SetAge(intpAge) // Updating of data is only possible via public method
            {
                        If(pAge>0 &&pAge
                        {         
                                    Age=pAge;
                        }
                        else
                        {
                                    throw new Exception(“Invalid Age”);
                        }
            }
}

Now our data is protected.

Client code will look like this.

Customer c=new Customer();
c.SetAge(55);
Console.WriteLine(c.GetAge());

c.SetAge(965);   // It will throw exception

In the above code snippet GetAge function which usually return the data is called Accessor method and SetAge function which updates data is called Mutator method.

Good news?

Now we are in C# things become much simpler. We can make use of properties instead of creating two functions.

public class Customer
{
            privateintpAge;           .
            .
            .
            publicintAge()
            {
                        get
                        {
                                    //Accessor
                                    returnpAge;
                        }
                        set
                        {                     
                                    //Mutator        
                                    If(value>0 && value
                                    {         
                                                pAge=value;
                                    }
                                    else
                                    {
                                                throw new Exception(“Invalid Age”);
                                    }
                        }
            }
}

Client code will look like this,

Customer c=new Customer();
c.Age=55;
Console.WriteLine(c.Age);

c.Age = 965;   // It will throw exception

What are indexers?

Indexers let us individual objects like a collections.

Consider the following example where we have a composition relationship between customer and address class.

public class Customer
{
            public string CustomerName{ get; set; }
            public string Address{ get; set; }

            private List<Address> Addresses;
}


public class Address
{
            publicpublic string City{get;set;}
            public string City{get;set;}
}

Now usually in order to access the address object, some functions will be exposed by customer class as follows.

public List<Address> GetAddersses()
{

            return Addresses;
}
public Address GetAddressAtIndex(int Index)
{

            return Addresses[Index];
}
public Addres GetAddressByCity(string CityName)
{
            foreach(Address a2 in Addresses)
            {
                        If(a2.CityName==cityName)
                        {

                                    return a2;
                        }

            }
}

In the client code one of these functions will be invoked using customer class object

Address a=MyCustomer.GetCustomerByCity(“Mumbai”);

Now indexers let us treat our customer object as collection and it will return address objects on passing some parameters.

We will create indexer inside Customer Class as follows,

public class Customer
{
            .
            .
            .
            public Address this[string CustomerName]
            {
                        get
                        {
                                    foreach(Address a2 in Addresses)
                                    {
                                                If(a2.CityName==cityName)
                                                {

                                                            return a2;
                                                }
                                    }

                        }

            }
}

Now we can use the following syntax and get the Address object.

Address a=MyCustomer[“Mumbai”];

-----------------
What are benefits and Limitation of using Viewstate for state management?

Following are the benefits of using Viewstate:-
  • No server resources are required because state is in a structure in the page code.
  • Simplicity.
  • States are retained automatically.
  • The values in view state are hashed, compressed, and encoded, thus representing a higher state of security than hidden fields.
  • View state is good for caching data in Web frame configurations because the data is cached on the client.
Following are limitation of using Viewstate:-
  • Page loading and posting performance decreases when large values are stored because view state is stored in the page.
  • Although view state stores data in a hashed format, it can still be tampered because it is stored in a hidden field on the page. The information in the hidden field can also be seen if the page output source is viewed directly, creating a potential security risk.
Below is sample of storing values in view state.

this.ViewState["EnterTime"] = DateTime.Now.ToString();

How can you use Hidden frames to cache client data?

This technique is implemented by creating a Hidden frame in page which will contain your data to be cached.

<FRAMESET cols="100%,*,*">
<FRAMESET rows="100%">
<FRAME src="data_of_frame1.html"></FRAMESET>
<FRAME src="data_of_hidden_frame.html">
<FRAME src="data_of_hidden_frame.html" frameborder="0" noresize scrolling="yes">
</FRAMESET>

Above is a sample of hidden frames where the first frame “data_of_frame1.html” is visible and the remaining frames are hidden by giving whole col section to first frame. 100 % is allocated to first frame and remaining frames thus remain hidden.

What are benefits and limitations of using Hidden frames?

Following are the benefits of using hidden frames:
  • You can cache more than one data field.
  • The ability to cache and access data items stored in different hidden forms.
  • The ability to access JScript® variable values stored in different frames if they come from the same site.
The limitations of using hidden frames are:
  • Hidden frames are not supported on all browsers.
  • Hidden frames data can be tampered thus creating security hole.
What are benefits and limitations of using Cookies?

Following are benefits of using cookies for state management:-
  • No server resources are required as they are stored in client.
  • They are light weight and simple to use
Following are limitation of using cookies:-
  • Most browsers place a 4096-byte limit on the size of a cookie, although support for 8192-byte cookies is becoming more common in the new browser and client-device versions available today.
  • Some users disable their browser or client device’s ability to receive cookies, thereby limiting the use of cookies.
  • Cookies can be tampered and thus creating a security hole.
  • Cookies can expire thus leading to inconsistency.
Below is sample code of implementing cookies

Request.Cookies.Add(New HttpCookie(“name”, “user1”))
----------------
What is a SESSION?

Session object store information between HTTP requests for a particular user.

Which are the various modes of storing ASP.NET session?
  • InProc: - In this mode Session, state is stored in the memory space of the Aspnet_wp.exe process. This is the default setting. If the IIS reboots or web application restarts then session state is lost.
  • StateServer: - In this mode Session state is serialized and stored in a separate process (Aspnet_state.exe); therefore, the state can be stored on a separate computer(a state server).
  • SQL SERVER: - In this mode Session, state is serialized and stored in a SQL Server database.
Session state can be specified in <sessionState> element of application configuration file. Using State Server and SQL SERVER session state can be shared across web farms but note this comes at speed cost as ASP.NET needs to serialize and deserialize data over network repeatedly.

Does session use cookies?

Yes, session use cookies. The session id value is stored in the browser client temp directory. This id is used to get the session data from the server in every post back.

Is Session_End event supported in all session modes?

Session_End event occurs only in “Inproc mode”. “State Server” and “SQL SERVER” do not have Session_End event.

How can we kill a user session?

Session.abandon

How is stored procedure different from functions?
  • Function cannot affect the state of the database which means we cannot perform CRUD operation on the database. Stored Procedure can affect the state of the database by using CRUD operations.
  • Store Procedure can return zero or n values whereas Function can return only one value.
  • Store Procedure can have input, output parameters for it whereas functions can have only input parameters.
  • Function can be called from Stored Procedure whereas Stored Procedure cannot be called from Function
How do we use stored procedure in ADO.NET and how do we provide parameters to the stored procedures?

ADO.NET provides the SqlCommand object, which provides the functionality of executing stored procedures. In the command type we need to provide the command type as stored procedure as shown in the below code snippet.

SqlCommand objCommand = new SqlCommand("sp_Insert", objConnection);
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.ExecuteNonQuery();


How do we use stored procedure in ADO.NET and how do we provide parameters to the stored procedures?

ADO.NET provides the SqlCommand object, which provides the functionality of executing stored procedures. In the command type we need to provide the command type as stored procedure as shown in the below code snippet.

SqlCommand objCommand = new SqlCommand("sp_Insert", objConnection);
objCommand.CommandType = CommandType.StoredProcedure;
objCommand.ExecuteNonQuery();

How can we force the connection object to close after my data reader is closed?

Command method Execute reader takes a parameter called as Command Behavior wherein we can specify saying close connection automatically after the Data reader is close.

PobjDataReader = pobjCommand.ExecuteReader (CommandBehavior.CloseConnection)\

How do you fill the dataset?

Create object of data adapter and call the fill command method of the adapter.

SqlDataAdapter objAdapter = new SqlDataAdapter(objCommand);
DataSet objDataset = new DataSet();
objAdapter.Fill(objDataset);

How can we save all data from dataset?

Dataset has “AcceptChanges” method, which commits all the changes since last time “Acceptchanges” has been executed.

How can we load multiple tables in a Dataset?

objCommand.CommandText = "Table1"
objDataAdapter.Fill(objDataSet, "Table1")
objCommand.CommandText = "Table2"
objDataAdapter.Fill(objDataSet, "Table2")

Above is a sample code, which shows how to load multiple “Data Table” objects in one “Dataset” object. Sample code shows two tables “Table1” and “Table2” in object ObjDataSet.

lstdata.DataSource = objDataSet.Tables("Table1").DefaultView

In order to refer “Table1” Data Table, use Tables collection of Datasets and the Default view object will give you the necessary output.

How can we add relation between tables in a Dataset? 

Dim objRelation As DataRelation
objRelation=New
DataRelation("CustomerAddresses",objDataSet.Tables("Customer").Columns("Custid")
,objDataSet.Tables("Addresses").Columns("Custid_fk"))
objDataSet.Relations.Add(objRelation)

Relations can be added between “Data Table” objects using the “Data Relation” object. Above sample, code is trying to build a relationship between “Customer” and “Addresses” “Data table” using “Customer Addresses” “Data Relation” object.

I want to force the data reader to return only schema of the data store rather than data.

PobjDataReader = pobjCommand.ExecuteReader (CommandBehavior.SchemaOnly)

How can we fine-tune the command object when we are expecting a single row?

Again, CommandBehaviour enumeration provides two values Single Result and Single Row. If you are expecting a single value then pass “CommandBehaviour.SingleResult” and the query is optimized accordingly, if you are expecting single row then pass “CommandBehaviour.SingleRow” and query is optimized according to single row.

Which is the best place to store connection string in .NET projects?

Config files are the best places to store connection strings. If it is a web-based application “Web.config” file will be used and if it is a windows application “App.config” files will be used.

How can we kill a user session?

Session.abandon

How do you upload a file in ASP.NET?

By using System.Web.HttpPostedFile class.

How do I send email message from ASP.NET?

ASP.NET provides two namespace SystemWEB.mailmessage class and System.Web.Mail.Smtpmail class. Just a small homework creates an Asp.NET project and send an email at shiv_koirala@yahoo.com. Do not Spam :-)

If cookies are disabled how will forms authentication work?

It will pass data through query strings.

What is scavenging?

When server running your ASP.NET application runs low on memory resources, items are removed from cache depending on cache item priority. Cache item priority is set when you add item to cache. By setting the cache item priority controls, the items scavenging are removed according to priority.

What are different types of caching using cache object of ASP.NET?

You can use two types of output caching to cache information that is to be transmitted to and displayed in a Web browser:
  • Page Output Caching
Page output caching adds the response of page to cache object. Later when page is requested page is displayed from cache rather than creating the   page object and displaying it. Page output caching is good if the site is fairly static.
  •  Page  Fragment Caching
If parts of the page are changing, you can wrap the static sections as user controls and cache the user controls using page fragment caching.

How can you cache different version of same page using ASP.NET cache object?

Output cache functionality is achieved by using “OutputCache” attribute on ASP.NET page header. Below is the syntax

<%@ OutputCache Duration="20" Location="Server" VaryByParam="state" VaryByCustom="minorversion" VaryByHeader="Accept-Language"%>
  • VaryByParam: - Caches different version depending on input parameters send through HTTP POST/GET.
  • VaryByHeader: - Caches different version depending on the contents of the page header.
  • VaryByCustom:-Lets you customize the way the cache handles page variations by declaring the attribute and overriding the GetVaryByCustomString handler.
  • VaryByControl:-Caches different versions of a user control based on the value of properties of ASP objects in the control.
How will implement Page Fragment Caching?

Page fragment caching involves the caching of a fragment of the page, rather than the entire page. When portions of the page are need to be dynamically created for each user request this is best method as compared to page caching. You can wrap Web Forms user control and cache the control so that these portions of the page do not need to be recreated each time.

What are abstract classes?

Abstract class is a half defined parent class. The full implementation of abstract class is defined by the child classes.

For example below code snippet shows a simple abstract class / half defined class called “DatabaseCommon” and later the concrete classes i.e. “SQLServer” and “Oracle” inherit and define a complete implementation for the same.

To define an abstract class we need to use the abstract keyword.

public abstract class DatabaseCommon
{
}
public  class SQLServer : DatabaseCommon
{
}
public  class Oracle : DatabaseCommon
{
}

What are abstract methods?

Abstract classes can have abstract methods. Abstract methods when defined in a parent class have to be implemented in the child classes. If abstract methods are not implemented it will throw a error.

Can we create an object of abstract class or an interface?

No.

An abstract with only abstract method, how is it different from interfaces?

If you define all methods, function, properties as abstract in abstract class it inhibits the same behavior as an interface.

What is difference between abstract classes and interfaces?


Can ASP.NET project run with out a Web.config file ?

Yes.

Can we have two Web.config file in a project ?

Yes we can , look at the below video  which explain’s why we need two web.config files.

Differentiate between Web.config vs machine.config file

“Web.config” files apply settings to each web application, while “Machine.config” file apply settings for all ASP.NET applications running on that machine.

What is Object Oriented Programming?

OOP is software designing technique where we think in terms of real world objects.

What is a Class and object?

Class is a blue print / template. Objects are instances of classes, in other words they bring life in class.  To use a class we need to create an object.

What are abstract classes?

Abstract class is a half defined parent class. The full implementation of abstract class is defined by the child classes.

For example below code snippet shows a simple abstract class / half defined class called “DatabaseCommon” and later the concrete classes i.e. “SQLServer” and “Oracle” inherit and define a complete implementation for the same.

To define an abstract class we need to use the abstract keyword.

public abstract class DatabaseCommon
{
}
public  class SQLServer : DatabaseCommon
{
}
public  class Oracle : DatabaseCommon
{
}

What are abstract methods?

Abstract classes can have abstract methods. Abstract methods when defined in a parent class have to be implemented in the child classes. If abstract methods are not implemented it will throw a error.

What is an Interface?

Interface is a contract that defines the signature of the functionality. It looks like a class but has no implementation. It has only empty definition of methods, functions, events, and indexer.

Interfaces provide forced implementation. For instance in the below code snippet we have created a simple interface called as “IDbCompulsory”. The below classes who implement interface “IDbCompulsory” has to provide implementation for “ExecSql”.

interface  IDbCompulsory
{
void ExecSql();
}
public  class SQLServer : IDbCompulsory
{
public void ExecSql()
{
// Here code for firing SQL Server SQL statements
// are written         
}
}
public  class Oracle : IDbCompulsory
{
public void ExecSql()
{
// Here code for firing Oracle SQL statements
// are written                     
}
} 

How many types of validation controls are provided by ASP.NET?

There are six main types of validation controls:-

RequiredFieldValidator
It checks whether the control have any value. It is used when you want the control should not be empty.

RangeValidator
It checks if the value in validated control is in that specific range. Example TxtCustomerCode should not be more than eight lengths.

CompareValidator
It checks that the value in controls should match some specific value. Example Textbox TxtPie should be equal to 3.14.

RegularExpressionValidator
When we want the control, value should match with a specific regular expression.

CustomValidator
It is used to define User Defined validation.

Validation Summary
It displays summary of all current validation errors on an ASP.NET page.

How can we force all the validation control to run?

Page.Validate

How can we check if all the validation control are valid and proper?

Using the Page.IsValid() property you can check whether all the validation are done.

If client side validation is enabled, will server side code still run ?

When client side validation is enabled server emit’s JavaScript code for the custom validators. However, note that does not mean that server side checks on custom validators do not execute. It does this redundant check two times, as some of the validators do not support client side scripting.

Which JavaScript file is referenced for validating the validators at the client side?

WebUIValidation.js JavaScript file installed at “aspnet_client” root IIS directory is used to validate the validation controls at the client side

How to disable client side script in validators?

Set ‘EnableClientScript’ to false.

How can I show the entire validation error message in a message box on the client side?

In validation summary set “ShowMessageBox” to true.

How can we identify that the Page is Post Back?

Page object has an “IsPostBack” property, which can be checked to know t the page is posted back.

What is the use of @ Register directives?

@Register directive informs the compiler of any custom server control added to the page.

What is the use of Smart Navigation property?

It’s a feature provided by ASP.NET to prevent flickering and redrawing when the page is posted back.

Can you explain “AutoPostBack”?

If we want the control to automatically post back in case of any event, we will need to check this attribute as true. For example on a Combo Box change  if we need to send the event immediately to the server side then we need to mark “AutoPostBack” attribute to true.

What is impersonation in ASP.NET?

By default, ASP.NET executes in the security context of a restricted user account on the local machine. Sometimes you need to access network resources such as a file on a shared drive, which requires additional permissions. One way to overcome this restriction is to use impersonation. With impersonation, ASP.NET can execute the request using the identity of the client who is making the request, or ASP.NET can impersonate a specific account you can specify the account in  web.config.

How can we identify that the Page is Post Back?

Page object has an “IsPostBack” property, which can be checked to know t the page is posted back.

What is the use of Smart Navigation property?

It’s a feature provided by ASP.NET to prevent flickering and redrawing when the page is posted back.

In which event are the controls fully loaded?

Page load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that view state is not fully loaded during this event.\

Where is View State information stored?

In HTML Hidden Fields.

What is the use of @ Register directives?

@Register directive informs the compiler of any custom server control added to the page.

What is AppSetting Section in “Web.Config” file?

Web.config file defines configuration for a web project. Using “AppSetting” section, we can define user-defined values. Example below is a “Connection String” section, which will be used throughout the project for database connection.

<Configuration>
<appSettings>
<add key="ConnectionString" value="server=xyz;pwd=www;database=testing" />
</appSettings>

What are Events?

Events are higher level of encapsulation over delegates. Events use delegates internally. Delegates are naked and when passed to any other code, the client code can invoke the delegate. Event provides a publisher / subscriber mechanism model.

So subscribers subscribe to the event and publisher then push messages to all the subscribers. Below is a simple code snippet for the same: -

Create a delegate and declare the event for the same.

public delegate void CallEveryone();
public event CallEveryone MyEvent;

Raise the event.

MyEvent();

Attached client methods to the event are fired / notified.

obj.MyEvent += Function1;

Do events have return type?

No, events do not have return type.

Can events have access modifiers?

Yes.

Can we have shared events

Yes, you can have shared events, do note only shared methods can raise shared events.

What is Namespace?

Namespace does two basic functionalities:-
  • It logically groupsclasses, for instance System.Web.UI logically groups UI related features like textboxes, list control etc.
  • In Object Oriented world, many times it is possible that programmers will use the same class name. Qualifying NameSpace with class names avoids this collision.
What is Difference between NameSpace and Assembly?

Following are the differences between namespace and assembly:
  • Assembly is physical grouping of logical units, Namespace, logically groupsclasses.
  • Namespace can span multiple assemblies while assembly is a physical unit like EXE , DLL etc.
What is ILDASM?

ILDASM is a simple tool which helps you to view IL code of a DLL or EXE. In order to view  IL code using ILDASM , go to visual studio command prompt and run “ILDASM.EXE”. Once ILDASM is running you view the IL code.

What is Manifest?

Assembly metadata is stored in Manifest. Manifest contains metadata which describes the following things :-
  • Version of assembly.
  • Security identity.
  • Scope of the assembly.
  • Resolve references to resources and classes.
The assembly manifest is stored in the DLL itself.

Where is the version information stored of an assembly?

Version information is stored in assembly inside the manifest.

Is versioning applicable to private assemblies?

Yes, versioning is applicable to private assemblies also.

What is the difference between data grid and grid view?

Grid view is a successor of data grid with following benefits: -
  • Grid view has automatic paging as compared to data grid where you need to write some code for paging.
  • Additional column types and rich design time capabilities.
What is the difference between Grid view, Data list and repeater?

Grid view and data grid by default display all the data in tabular format i.e. in table and rows.  Developer has no control to change the table data display of datagrid.

Data list also displays data in a table but gives some flexibility in terms of displaying data row wise and column wise using the repeat direction property.

Repeater control is highly customizable. It does not display data in table by default.  So you can customize from scratch the way you want to display data.
---------------------
What is operator overloading?

Operator overloading is a concept of polymorphism where you can redefine operators like +, - , * etc with additional functionalities.

For instance we can redefine the + functionalities to add objects like obj1 + obj2.  Below is simple code snippet which redefines + operator.

class SomeClass
{

private int someValue;

public SomeClass(int val)
{
 someValue = val;
}

public static SomeClass operator +(SomeClass arg1, SomeClass arg2)
{
return new SomeClass(arg1.someValue +  arg2.someValue);
}

}

You can now use the + operator to add objects of type someclass as shown in the below code snipet.

Obj = obj1 + obj2;

What are abstract classes?

Abstract class is a half defined parent class. The full implementation of abstract class is defined by the child classes.

For example below code snippet shows a simple abstract class / half defined class called “DatabaseCommon” and later the concrete classes i.e. “SQLServer” and “Oracle” inherit and define a complete implementation for the same.

To define an abstract class we need to use the abstract keyword.

public abstract class DatabaseCommon
{
}
public  class SQLServer : DatabaseCommon
{
}
public  class Oracle : DatabaseCommon
{
}

What are abstract methods?

Abstract classes can have abstract methods. Abstract methods when defined in a parent class have to be implemented in the child classes. If abstract methods are not implemented it will throw a error.

What is an Interface?

Interface is a contract that defines the signature of the functionality. It looks like a class but has no implementation. It has only empty definition of methods, functions, events, and indexer.

Interfaces provide forced implementation. For instance in the below code snippet we have created a simple interface called as “IDbCompulsory”. The below classes who implement interface “IDbCompulsory” has to provide implementation for “ExecSql”.

interface  IDbCompulsory
{
void ExecSql();
}
public  class SQLServer : IDbCompulsory
{
public void ExecSql()
{
// Here code for firing SQL Server SQL statements
// are written         
}
}
public  class Oracle : IDbCompulsory
{
public void ExecSql()
{
// Here code for firing Oracle SQL statements
// are written                     
}
} 
------------------

Design Pattern in .NET

What are Design Patterns?

Design patterns are recurring solution to recurring problems in software architecture.

Which Design Patterns are you familiar with?

Left up to you pick any three patterns which you are known and have used in your project and talk about it. By this interviewer will come know that you are not new to Design Patterns.

Can you explain Singleton Pattern?

Singleton pattern helps us to create a single instance of an object which can be shared across project. Main use of singleton pattern is for global data sharing and caching.

What is MVC, MVP and MVVM pattern?

All the above design patterns come in presentation pattern category and help to remove any kind of cluttered code in UI like manipulation of user interfaces and maintaining state. Thus it keeps your UI code cleaner and better to maintain.

MVC pattern divides the architecture in to 3 part model, view and controller. The first request comes to the controller and the controller then decides which view to be displayed and ties up the model with the view accordingly.

MVP (Model view presenter) has the same goals as MVC i.e. separating the UI from the model. It does the same by using a presenter class. The UI talks via an interface to the presenter class and the presenter class talks with the model.

MVVM is an architectural pattern with the focus of removing UI cluttered code. It does the same by using an extra class called as view model. MVVM is mostly suitable for SilverLight and WPF projects because of the rich bindings provided by the technologies.
Does Single is a way of implanting Singleton Pattern?

Yes.

See the following training video on Design Pattern: -

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

What is a Composite Pattern?

During Programming there are times when we have a collection of objects with us and we want to treat collection of objects and individual objects uniformly.

Example:
  • Let’s say you are creating a complex user controls.Now the best part is controls like textbox, button and label should be treated in the samemanner we treat controls like panel which in turn may consist of many controls.
    Here Composite pattern comes to picture.
  • Let’s say you are working on a logic which consist of working with file system. In this case you will be mainly working with files. Files may indicate simple flat files or folders whichcontain one or more files internally.We implement Composite pattern in this situation.
How to implement Composite Pattern?

Let’s talk more about the control creation demo discussed above and let see how to implement composite pattern.

1. When it comes to implementing Composite pattern first thing we will do is identify all the    
    container (control which can contain more controls) and individual self-contained controls.

Let’s say individual controls are Button and textbox. Composite control is Panel.

public class Panel{}
public class Button{}
public class Textbox{}

2. We want to treat both of them uniformly. Is simple words these two should be
    belonging to same family and for that we need an interface containing Render Method

public interface IControl{void Render();}

3. Implement the interface in all the classes and implement Render Method.

public class Textbox:IControl
{
Public void Render()
{

 //Render Textbox
            }
}
public class Button:IControl
{
Public void Render()
{

 //Render Button
            }
}
public class Panel:IControl
{
public List<IControl>ChildControls{get;set;}
Public void Render()
{
            //Render Panel Start
            foreach(IControli in ChildControls)
            {

                        i.Render();
                        }

            //Render Panel End
            }
}

That’s it this is the composite pattern. A group of object and individual object will be treated same now.

See following video on Composite Pattern: -

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

Literal VS Label (ASP.NET Interview questions)

Recently one of our students had gone for aASP.NET Interview and he was asked this weird question “When should you use Literal VSLabel ?”. Honestly at that time I did not know the answer and I thought it’s not so important either.

By default whenever I want to put a text I normally use a label as many ASP.NET developer’s do.
                              

Later in the evening when I hunted around my whole perspective to look at ASP.NET Label server control changed.

I did the following simple experiments.

Experiment 1 :-First thing I dragged a label and literal on simple form as shown below.

                              

I ran the project and out of curiosity when I saw the HTML results I was stunned. Label was emitting out a “SPAN” tag while literal was not.
                               

I did some more experiments further i put a bold HTML tag to see if probably there was difference in formatting.


Again the visual output was absolutely same , both where showing bold output but the label was adding an extra SPAN tag while literal was light weight.


Conclusion 1:- If you want to just display text with formatting start with a literal. Because literal controls are light weight as compared to label.

Further googling and reading things I was introduced to one more property in literal called as “Mode”. This feature again made my “Conclusion 1” more stronger that always first start with a literal control to display text.
                                 

If I have HTML in my literal text and if I choose “Transform” the HTML will be parsed and displayed accordingly. But  if I choose  encode then the HTML will be displayed as it on the browser.

Means if you  havethe below HTML code for literal , please note the  html tag inside it.


The display will be as follows, means the HTML is displayed as it is.
                                

Now the climax  when should we use “Label” server controls. After further hunting we can not apply CSS to literal , but we can apply CSS to Label. That’s the whole reason why he emits those extra “SPAN” tag so that CSS can be referred.
                               

Conclusion 2:- If you are applying CSS to your text then you have no way but use a Label.

So next time you get this googly weird ASP.NET Interview questions , below is the answer:-

“As a good practice we should always use a literal control as its lightweight and serves almost all purpose. But if we want to apply CSS to a text then we need to use the label control.”

Preparing for .NET and ASP.NET Interview’s start from the below video which talks about how questions are asked in .NET and ASP.NET Interviews.

 ----------------
What is difference between Dataset.Clone and Dataset.Copy?

Clone: - It only copies structure, does not copy data.

Copy: - Copies both structure and data.

Can you explain the difference between an ADO.NET Dataset and an ADO Record set?

There two main basic differences between record set and dataset:-
  • With dataset you can retrieve data from two databases like oracle and sql server and merge them in one dataset , with record set this is not possible
  • All representation of Dataset is using XML while record set uses COM.
  • Record set cannot be transmitted on HTTP while Dataset can be.
See following video on Dataset is a disconnect while datareader is connected: -

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

Encrypting web.config files in ASP.NET

Encryption can be done in ASP.NET using the “aspnet_regiis.exe” tool. There are two encryption options provided by ASP.NET: -

Windows Data Protection API (DPAPI) Provider(DataProtectionConfigurationProvider)-this provider uses the built-in cryptography capabilities of Windows to encrypt and decrypt the configuration sections. By default this provider uses the machine's key.

RSA Protected Configuration Provider (RSAProtectedConfigurationProvider) - uses RSA public key encryption to encrypt/decrypt the configuration sections. With this provider you need to create key containers that hold the public and private keys used for encrypting and decrypting the configuration information.

While encrypting the config files we can choose what kind of provider we need for encryption. So let’s understand step by step how we can actually encrypt the web.config file sections.

Step 1:- Go to the command prompt of the framework.

Step 2:- Run the aspnet_regiis.exe as shown in the figure. We have provided the section which we need to encrypt and the provider. If the command is successfully executed, you should get a succeeded message of encryption. You can see we have decrypted the appSettings section. We have also shown how the unencrypted config file looks after running aspnet_regiis.exe.

Step 3:- Once the file is encrypted you can use the same in your program in a normal fashion.  For instance the below defined appSetting key “MyValue” in figure “aspnet_regiis.exe in Action” can be displayed simply by:-

Response.Write(WebConfigurationManager.AppSettings("MyValue").ToString())

You do not need to do any kind if decryption inside your program again.

Figure 21.4 shows how the plain text is further changed to an encrypted form using aspnet_regiis.exe.
                                 

Below is the aspnet_regiis in different forms for your referral.

-- Generic form for encrypting the Web.config file for a particular website...
aspnet_regiis.exe -pef section physical_directory –prov provider
   -- or --
aspnet_regiis.exe -pe section -app virtual_directory –prov provider

-- Concrete example of encrypting the Web.config file for a particular website

aspnet_regiis.exe -pef "connectionStrings" "C:\Inetpub\wwwroot\MySite" –prov "DataProtectionConfigurationProvider"
   -- or --
aspnet_regiis.exe -pe "connectionStrings" -app "/MyWebSite" –prov "DataProtectionConfigurationProvider"

-- Generic form for decrypting the Web.config file for a particular website...
aspnet_regiis.exe -pdf section physical_directory
   -- or --
aspnet_regiis.exe -pd section -app virtual_directory

-- Concrete example of decrypting the Web.config file for a particular website...
aspnet_regiis.exe -pdf "connectionStrings" "C:\Inetpub\wwwroot\MyWebSite"
   -- or --
aspnet_regiis.exe -pd "connectionStrings" -app "/MyWebSite"

See following video on Web.config transformation: -

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

Explain Query String in ASP.NET and what are benefits and limitations of using Query Strings?

A query string is information sent to the server appended to the end of a page URL.

Following are the benefits of using query string for state management: -
  • No server resources are required. The query string containing in the HTTP requests for a specific URL.
  • All browsers support query strings.
Following are limitations of query string: -
  • Query string data is directly visible to user thus leading to security problems.-
  • Most browsers and client devices impose a 255-character limit on URL length.
Below is a sample “Login” query string passed in URL

This query string data can then be requested later by using Request.QueryString(“login”).
 --------------------
What is an application object?

Application object is used when we want data to be shared across users globally in an ASP.NET application.

What is the use of cache object?

It also does the same thing as the application object i.e. sharing and caching global data across ASP.NET pages in a web application.

What is the difference between Cache object and application object?

The main difference between the Cache and Application objects is that the Cache object provides features, such as dependencies and expiration policies.

How can get access to cache object?

The Cache object is defined in the ‘System.Web.Caching’ namespace. You can get a reference to the Cache object by using the Cache property of the HttpContext class in the ‘System.Web’ namespace or by using the Cache property of the Page object.

What are dependencies in cache and types of dependencies?

When you add an item to the cache, you can define dependency relationships that can force that item to be removed from the cache under specific activities of dependencies.Example if the cache object is dependent on file and when the file data changes you want the cache object to be update. Following are the supported dependency:-
  • File dependency: - Allows you to invalidate a specific cache item when a disk based file or files change.
  • Time-based expiration: - Allows you to invalidate a specific cache item depending on predefined time.
  • Key dependency:-Allows you to invalidate a specific cache item depending when another cached item changes.
Can you show a simple code showing file dependency in cache?

PartialClass Default_aspx

PublicSub displayAnnouncement()
Dim announcement AsString
If Cache(“announcement”) IsNothingThen
Dim file AsNew _
System.IO.StreamReader _
(Server.MapPath(“announcement.txt”))
announcement = file.ReadToEnd
file.Close()
Dim depends AsNew _
System.Web.Caching.CacheDependency _
(Server.MapPath(“announcement.txt”))
Cache.Insert(“announcement”, announcement, depends)
EndIf
Response.Write(CType(Cache(“announcement”), String))
EndSub

PrivateSub Page_Init(ByVal sender AsObject, ByVal e As                       
        System.EventArgs) HandlesMe.Init
displayAnnouncement()
EndSub
End Class

Above given method displayAnnouncement() displays banner text from Announcement.txt file which is lying in application path of the web directory. Above method, first checks whether the Cache object is nothing, if the cache object is nothing then it moves further to load the cache data from the file. Whenever the file data changes the cache object is removed and set to nothing.

See following video on ASP.NET Authentication, Authorization, Principal and Identity objects:-

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

What is CodeLens?

Code lens is a new feature in visual studio 2013 which helps us to understand three important things about our code while we are coding inside visual studio.

All these three things(Impact, test and latest) are seen right above your class / method when you code in visual studio as shown in the below figure.
                                                    

Impact: - First thing code lens shows is when we change the code what isthe impact of those changes. For instancein the above figure you can see it stating that if you make any changes to the log method it will be impact 1 reference.

If you click on references further it will also show which the classes it’s referencing. With this we come to know the level of impact this change will have further.

In the below screen it’s stating that “ConsoleApplication2” and “UnitTest1.cs” are the classes which.
                                 

If you further click on “Show on Code Map” menu you should see a graphical representation of dependencies.
                             
Test :- Second important thing code lens tells is whether this method was unit tested or not.  For instance you can see it say’s 1 passing means this method was unit tested.
                                                                                                             
Latest: -Third thing it tells where this is a latest code or not. You can see the last menu which states this is not a latest code and you need to do a get latest from the server.
-------------------
What are the various ways of authentication techniques in ASP.NET?

There are 3 major ways of doing authentication and authorization:
  • Windows: - In this mode the users are stored in windows local user groups.
  • Forms: - In this mode we create a login screen and use the forms authentication class to do validations. It’s a ticket based authentication.
  • Passport: -In this mode the users are validated from Microsoft sites like hotmail , devhood , MSN etc , ticket is generated and that ticket can be used to do  authentication and authorization in your web application.
How do I sign out in forms authentication?

FormsAuthentication.Signout()

If cookies are disabled how will forms authentication work?

It will pass data through query strings.

How do we implement windows authentication?

  • Create users in your local windows user group.
  • In web.config file set the authentication mode to windows.
  • In web.config file set <deny users="?"/>.
Once you do the above three steps your asp.net pages will authenticated and authorized from the users stored in windows local user group.

How can we do single sign-on in ASP.NET?

For single sign-on we need to use forms authentication and put the same machine key in the web.config files of all web applications who will participate in single sign on.

See following video on implementing ASP.NET Forms Authentication: -

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

What are the three different level of IIS isolation?

IIS has three level of isolation:-

LOW (IIS process):- In this main IIS, process, and ASP.NET application run in same process. So if any one crashes the other is also affected. Example let us say (well this is not possible) I have hosted yahoo, hotmail .amazon and goggle on a single PC. So all application and the IIS process runs on the same process. In case any website crashes, it affects everyone.

                            

Medium (Pooled):- In Medium pooled scenario, the IIS, and web application run in different process. Therefore, in this case there are two processes process1 and process2. In process1, the IIS process is running and in process2, we have all Web application running.

                            

High (Isolated):- In high isolated scenario every process is running is their own process. In below figure there are five processes and every one handling individual application. This consumes heavy memory but has highest reliability.

                            

See following video on importance of session and viewstate: -

-----------------
How can we create custom controls in ASP.NET?

User controls are created using .ASCX in ASP.NET. After .ASCX file is created you need to two things in order that the ASCX can be used in project:.
<%@ Register tag prefix="Accounting" Tag name="footer" Src="Footer.ascx" %>
  • Now to use the above accounting footer in page you can use the below directive.
<Accounting: footer runat="server" />

How many types of validation controls are provided by ASP.NET?

There are six main types of validation controls:-

RequiredFieldValidator
It checks whether the control have any value. It is used when you want the control should not be empty.

RangeValidator
It checks if the value in validated control is in that specific range. Example TxtCustomerCode should not be more than eight lengths.

CompareValidator
It checks that the value in controls should match some specific value. Example Textbox TxtPie should be equal to 3.14.

RegularExpressionValidator
When we want the control, value should match with a specific regular expression.

CustomValidator
It is used to define User Defined validation.

Validation Summary
It displays summary of all current validation errors on an ASP.NET page.

How can we force all the validation control to run?

Page.Validate

How can we check if all the validation control is valid and proper?

Using the Page.IsValid () property you can check whether all the validation are done.
---------------
What is ViewState?

Viewstate is a built-in structure for automatically retaining values between multiple requests for the same page. Viewstate is internally maintained as a hidden field on the page but is hashed, providing greater security than developer-implemented hidden fields do.

How do we ensure viewstate is not tampered?

View state is a simple HTML hidden field. So it’s possible very much possible that some one can tamper this hidden field easily.  To ensure that viewstate is not tampered we can set the  “EnableViewStateMac” attribute to true. This attribute is found in the “page” directive in ASPX page.Below is a simple code snippet which shows how to use the same.

<%@ Page EnableViewStateMac="true" %>

Does the performance for viewstate vary according to User controls?

Performance of viewstate varies depending on the type of server control to which it is applied. Label, TextBox, CheckBox, RadioButton, and HyperLink are server controls that perform well with ViewState. DropDownList, ListBox, DataGrid, and DataList suffer from poor performance because of their size and the large amounts of data making roundtrips to the server.
------------------
What is nested Classes?

Nested classes are classes within classes.

If you create the child class object which constructor will fire first?

public class class1
{
public  class1(){}
}

public class class2 : class1
{
public  class2(){}
}

Parent class constructor will fire first.

In what instances you will declare a constructor to be private?

When we create a private constructor, we cannot create object of the class.  Private constructors are used when we want only a single instance of the class to be created and externally no one can use the ‘new’ keyword to create the object.

Can we have different access modifiers on get/set methods of a property?

Yes, we can have different access modifiers. The below code will compile perfectly well.

public string CustName
{
    get
    {
        return _Custname;
    }
    protected set
    {
Custname = value;
    }
}
---------------------
What is the difference between “Web farms” and “Web garden”?

“Web farms” are used to have some redundancy to minimize failures and to meet heavy load demands.

It consists of two or more web server of the same configuration and they stream the same kind of contents. When any request comes there is switching / routing logic, which decides which web server from the farm, handles the request. For instance, we have two servers “Server1” and “Server2” which have the same configuration and content. Therefore, there is a special switch, which stands in between these two servers and the users and routes the request accordingly.


Above figure explains in detail how web farm work. You can see there is a router in between which takes a request and sees which one of the server is least loaded and forwards the request to that server. Therefore, for request1 it route is server1, for request2 it routes server2, for request3 it routes to server3 and final request4 is routed to server4. So you can see because we have web farm at place server1 and server2 are loaded with two request each rather than one server loading to full. One more advantage of using this kind of architecture is if one of the servers goes down we can still run with the other server thus having 24x7 uptime.

The routing logic can be a number of different options: -
  • Round robin: Each node gets a request sent to it “in turn”. Therefore, server1 gets a request, then server2 again, then server1, then server2 again.  As shown in the above figure.
  • Least Active: Whichever node show to have the lowest number of current connects gets new connects sent to it. This is good to help keep the load balanced between the server nodes.
  • Fastest Reply: Whichever node replies faster is the one that gets new requests. This is also a good option - especially if there are nodes that might not be “equal” in performance. If one performs better than the other, then send more requests there rather than which is moving slowly?
Before we try to understand what a web garden is let’s try to understand how IIS handles processes. All requests to IIS are routed to “aspnet_wp.exe” for IIS 5.0 and “w3wp.exe” for IIS 6.0. In normal case i.e. without web garden, we have one worker process instance (“aspnet_wp.exe” / “w3wp.exe”) across all requests. This one instance of worker process uses the CPU processor as directed by the operating system.


However, when we enable web garden for a web server it creates different instances of the worker process and each of these worker process runs on different CPU. You can see in the below diagram we have different worker process instances created which run on different CPU’s.


In short, we can define a model in which multiple processes run on multiple CPUs in a single server machine are termed as Web garden.

How do we configure “Web Garden”?

“Web garden” can be configured by using process model settings in “machine.config” or “Web.config” file. The configuration section is named <process Model> and is shown in

The following example. The process model is enabled by default (enable=”true”). Below is the snippet from config file.

<process model="">
enable=”true”
timeout=”infinite”
idle Timeout=”infinite”
shutdown Timeout=”0:00:05"
requestLimit=”infinite”
requestQueueLimit=”5000"
memoryLimit=”80"
webGarden=”false”
cpuMask=”12"
userName=””
password=””
logLevel=”errors”
clientConnectedCheck=”0:00:05"
/>

From the above process model section for web garden, we are concerned with only two attributes “web garden” and “cpuMask”.

WebGarden: - Controls CPU affinity. True indicates that processes should be affinities to the corresponding CPU. The default is False.

CpuMask:- Specifies which processors on a multiprocessor server are eligible to run ASP.NET processes. The cpuMask value specifies a bit pattern that indicates the CPUs eligible to run ASP.NET threads. ASP.NET launches one worker process for each eligible CPU. If web Garden is set to false, cpuMask is ignored and only one worker process will run regardless of the number of processors in the machine. If web Garden is set to true, ASP.NET launches one worker process for each CPU that corresponds to a set bit in cpuMask. The default value of cpuMask is 0xffffffff. 

Below are detail steps of how to implement web garden
  • Click Start and then click Run. 
  • Type calc.exe and then click OK.
  • Go to View menu, click Scientific.
  • Go to View menu, click Binary.
  • Use zero and one to specify the processors ASP.NET can or cannot use.
Use one for the processor that you want to use for ASP.NET. Use 0 for the processor that you do not want to use for ASP.NET. For example, if you want to use the first two processors for ASP.NET of a four-processor computer, type 1100.
  • On the View menu, click Decimal. Note the decimal number.
  • Open the Web.config or machine.config file in a text editor such as Notepad. The Web.config file is located in the folder where the application is saved.
  • In the Web.config file, add the process Model configuration element under the System. Web element. Before adding <process Model> to Web.config file, the user has to make sure that the allow Definition attribute in the <process Model> section of the Web.config file is set to everywhere.
  • Add and then set the web Garden attribute of the process Model element to True.
  • Add and then set the cpuMask attribute of the process Model element to the result that is determined in your calculation.
Do not preface the number with zerox because the result of the calculation is a decimal number. The following example demonstrates the process Model element that is configured to enable only the first two processors of a four-processor computer.

<processmodel>
enable=”true”
webGarden=”true”
cpuMask=”12" />

Save the Web.config file. The ASP.NET application automatically restarts and uses only the specified processors.

See following video on ASP.NET Web.config transformation: -

------------
Explain in detail the fundamental of connection pooling?

When a connection is opened first time, a connection pool is created and is based on the exact match of the connection string given to create the connection object. Connection pooling only works if the connection string is the same. If the connection string is different, then a new connection will be opened, and connection pooling will not be used.
                                           

Let us try to explain the same pictorially. In the above figure, you can see there are three requests “Request1”, “Request2”, and “Request3”.  “Request1” and “Request3” have same connection string so no new connection object is created for “Request3” as the connection string is same. They share the same object “ConObject1”. However, new object “ConObject2” is created for “Request2” as the connection string is different.

Note: - The difference between the connection string is that one has “User id=sa” and other has “User id=Testing”.

What is Maximum Pool Size in ADO.NET Connection String?

Maximum pool size decides the maximum number of connection objects to be pooled. Ifthe maximum pool size is reached and there is no usable connection available the requestis queued until connections are released back in to pool. So it’s always a good habit tocall the close or dispose method of the connection as soon as you have finishedwork with the connection object.

How to enable and disable connection pooling?

For .NET it is enabled by default but if you want to just make yourself double sure, set Pooling=true inthe connection string. To disable connection pooling set Pooling=false in connectionstring if it is an ADO.NET Connection.

If it is an OLEDBConnection object set OLEDB Services=-4 in the connection string.

See following video on ADO.NET Connection pooling: -

--------------
How can we fine-tune the command object when we are expecting a single row?

Again, CommandBehaviour enumeration provides two values Single Result and Single Row. If you are expecting a single value then pass “CommandBehaviour.SingleResult” and the query is optimized accordingly, if you are expecting single row then pass “CommandBehaviour.SingleRow” and query is optimized according to single row.

Which is the best place to store connection string in .NET projects?

Config files are the best places to store connection strings. If it is a web-based application “Web.config” file will be used and if it is a windows application “App.config” files will be used.

How do you fill the dataset?     

Create object ofdata adapterand call the fill command method of the adapter.

SqlDataAdapter objAdapter = new SqlDataAdapter(objCommand);
DataSet objDataset = new DataSet();
objAdapter.Fill(objDataset);

What are the various methods provided by the dataset object to generate XML?

  • ReadXML
                 Read’s a XML document in to Dataset.
  • GetXML
                 This is a function, which returns the string containing XML document.
  • Writexml
                 This writes a XML data to disk.

How can we save all data from dataset?

Dataset has “AcceptChanges” method, which commits all the changes since last time “Acceptchanges” has been executed.

See following video on dataset is a disconnect while datareader is connected: -

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

 

How can we identify that the Page is Post Back?

Page object has an “IsPostBack” property, which can be checked to know t the page is posted back.

What is the use of @ Register directives?

@Register directive informs the compiler of any custom server control added to the page.

What is the use of Smart Navigation property?

It’s a feature provided by ASP.NET to prevent flickering and redrawing when the page is posted back.

What is AppSetting Section in “Web.Config” file?

Web.config file defines configuration for a web project. Using “AppSetting” section, we can define user-defined values. Example below is a “Connection String” section, which will be used throughout the project for database connection.

<Configuration>
<appSettings>
<add key="ConnectionString" value="server=xyz;pwd=www;database=testing" />
</appSettings>

Where is View State information stored?

In HTML Hidden Fields.

How can we create custom controls in ASP.NET?

User controls are created using .ASCX in ASP.NET. After .ASCX file is created you need to two things in order that the ASCX can be used in project:.
<%@ Register tag prefix="Accounting" Tag name="footer" Src="Footer.ascx" %>
  • Now to use the above accounting footer in page you can use the below directive.
<Accounting: footer runat="server" />

See following video on implementing ASP.NET Forms Authentication: -

------------------
What are Httphandlers and HttpModules?

Handlers and modules helps you inject pre-processing logic before the ASP.NET request reaches the website.

One of the scenarios where you would like use them is, before request reaches on the server you would like to check if the user has authenticated or not.

What is the difference between Httphandlers and HttpModules?

Httphandlers is an extension based processor. In other words the pre-processing logic is invoked depending on file extensions.

Httpmodule is an event based processor. In other words ASP.NET emits lot of event like BeginRequest, AuthenticateRequest etc; we can write login functionality in those events using Httpmodule.

How do we write a Httphandler ?
  • Create a class and implement “IHttpHandler”.
public class clsHttpHandler : IHttpHandler
{

    public bool IsReusable
    {
        get { return true; }
    }

    public void ProcessRequest(HttpContext context)
    {
       // Put implementation here.
    }
}
  • Define implementation for “processrequest” method.
  • Register the class in web.config with file extension in httphandler tag.
<httpHandlers>
<add verb="*" path="*.gif" type="clsHttpHandler"/>
</httpHandlers>

How do we write anHttpModule?
  • Create a class and implement IHttpModule interface.
  • Attach events with your methods and put implementation in those events as shown in the below code snippet.
public class clsHttpModule : IHttpModule
{

    public void Init(HttpApplication context)
    {
       this.httpApp = context;
       httpApp.Context.Response.Clear();
       httpApp.AuthenticateRequest += new EventHandler(OnAuthentication);
       httpApp.AuthorizeRequest += new EventHandler(OnAuthorization);
       httpApp.BeginRequest += new EventHandler(OnBeginrequest);
       httpApp.EndRequest += new EventHandler(OnEndRequest);
       httpApp.ResolveRequestCache += new EventH

    }
    void OnUpdateRequestCache(object sender, EventArgs a)
    {
       //Implementation
    }
    void OnReleaseRequestState(object sender, EventArgs a)
    {
       //Implementation
    }
    void OnPostRequestHandlerExecute(object sender, EventArgs a)
    {
       //Implementation
    }
    void OnPreRequestHandlerExecute(object sender, EventArgs a)
    {
       //Implementation
    }
    void OnAcquireRequestState(object sender, EventArgs a)
    {
       //Implementation
    }
    void OnResolveRequestCache(object sender, EventArgs a)
    {
        //Implementation
    }
    void OnAuthorization(object sender, EventArgs a)
    {
        //Implementation
    }
    void OnAuthentication(object sender, EventArgs a)
    {

        //Implementation
    }
    void OnBeginrequest(object sender, EventArgs a)
    {

        //Implementation
    }
    void OnEndRequest(object sender, EventArgs a)
    {
       //Implementation

    }

}
  • Register the class in web.config in httpmodule tag as shown in the below code snippet.
<httpModules>
<add name="clsHttpModule" type="clsHttpModule"/>
</httpModules>

See following video on Authentication and Authorization: -

----------------
Can you explain Lazy Loading?

Lazy loading is a concept where we delay the loading of the object unit the point where we need it. Putting in simple words on demand object loading rather than loading the objects unnecessarily.

For example consider the below example where we have a simple “Customer” class and this “Customer” class has many  “Order” objects inside it. Have a close look at the constructor of the “Customer” class. When the “Customer” object is created it also loads the “Order” object at that moment. So even if we need or do not need the address object , it’s still loaded.

But how about just loading the “Customer” object initiallyand then on demand basis load the “Order” object.

public class Customer
{
private List<Order> _Orders= null;
public Customer()
{
            _CustomerName = "Shiv";
            _Orders = LoadOrders(); // Loads the address object even though //not needed

}
private List<Order> LoadOrders()
{
            List<Order> temp = new List<Order>();
            Order o = new Order();
            o.OrderNumber = "ord1001";
            temp.Add(o);
            o = new Order();
            o.OrderNumber = "ord1002";
            temp.Add(o);
            return temp;
}
}

So let’s consider you have client code which consumes the “Customer” class as shown below. So when the “Customer” object is created no “Order” objects should  be loaded at that moment. But as soon as the “foreach” loop runs you would like to load the “Order” object at that point ( on demand object loading).

Customer o = new Customer(); // Address object not loaded
Console.WriteLine(o.CustomerName);
foreach (Order o1 in o.Orders) // Load address object only at this moment
{
         Console.WriteLine(o1.OrderNumber);
}

What are the advantages/disadvantages of lazy loading?

Below are the advantages of lazy loading:-
  • Minimizes start up time of the application.
  • Application consumes less memory because of on-demand loading.
  • Unnecessary database SQL execution is avoided.
The disadvantage is that the code becomes complicated. As we need to do checks if the loading is needed or not. So must be there is a slight decrease in performance.

But the advantages of are far more than the disadvantages.

See following video on Lazy Loading Design Pattern: -

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

What are Events?

Events are higher level of encapsulation over delegates. Events use delegates internally. Delegates are naked and when passed to any other code, the client code can invoke the delegate. Event provides a publisher / subscriber mechanism model.

So subscribers subscribe to the event and publisher then push messages to all the subscribers. Below is a simple code snippet for the same: -

Create a delegate and declare the event for the same.

public delegate void CallEveryone();
public event CallEveryone MyEvent;

Raise the event.

MyEvent();

Attached client methods to the event are fired / notified.

obj.MyEvent += Function1;

Do events have return type?

No, events do not have return type.

Can events have access modifiers?

Yes.

Can we have shared events?

Yes, you can have shared events, do note only shared methods can raise shared events.
--------------------

Can we have two “web.config” files in one webapplication?( ASP.NET Interview questions with answers)

June 18, 2014 at 4:17pm
Yes, you can have two web.config files in web application.

In what scenarios will a project have two Web.configfiles ?

When developers develop application they divide project in to modules and many times these modules are hierarchically connected. For instance we are creating a web application for an organization which has departments.

We would like to divide our project source code in to modules as shown below. And every module will have their own configuration. Below is a simple web application project with two modules “Accounts” and “Sales”.

                                

So the main organization site has a config file at the root level followed by config files inside each module.

                                 

So let’s say if you are browsing “Home.aspx” from sales folder then “Web.config” file in the sales folder will get precedence. If the configuration is not found then it fall back to the “Web.config” file of the main directory.
-------------------
What is an IL code?

It’s a CPU independent partially compiled code.

Note: - Half compiled means this code is not yet compiled to machine/CPU specific instructions.

Why IL code is not fully compiled?

We do not know in what kind of environment.NET code will run. In other words we do not know what can be the end operating system, CPU configuration, machine configuration, security configuration etc. So the IL code is half compiled and on runtime this code is compiled to machine specific using the environmental properties (CPU, OS, machine configuration etc).

Who compiles the IL code and how does it work?

IL code is compiled by JIT (Just in time compiler).

Is it possible to view the IL code?

Yes by using ILDASM simple tool we can view an IL code of a DLL or EXE. In order to view IL code using ILDASM, go to visual studio command prompt and run “ILDASM.EXE”. Once ILDASM is running you view the IL code.
------------------

Write a note on "Array of Arrays”? ( .NET Interview questions with answers)

June 23, 2014 at 10:54am
This array interview question was asked in Wipro banglore to a .NET fresher.

Array of Array’s is also termed as “Jagged” array.  Arrays are zero indexed, means if you create an array of size 2 the first element starts at “0” and the second element starts at “1”.
For example below is a simple C# array code with a size of value “2”.

int[] mainarr = new int[2]; // Array with 2 values

So if you want to set values, you need to specify “0” for the first element and “1” for the second element.

mainarr[0] = 1;
mainarr[1] = 2;

So if we visualize the array picture it looks something as shown below. You have two array values with “0” and “1” index.

                                                             

If you want to display the second element you need to specify “1” in the index as shown in the below code.

Console.WriteLine(mainarr[1]); //Displays the 2nd element from the array

Now to create array of array ( jagged array) you need to put two square brackets “[][]”. The below code has created an array with length of 2 and every array index can have more array’s inside it.

int[][] mainarr = new int[2][];

So now we can set more array structure inside other array as shown in the below code.

mainarr[0] = new int[2];
mainarr[1] = new int[3];

So if visualize the array structure it looks as shown below. We have one main array of length 2 and each index having an array inside it. The first index i.e. “0” has array size of “2” and the second array index having a size of “3”.

                                              

So if you want to display the third array from the main array’s second element you can refer as shown in the below code.

Console.WriteLine(mainarr[1][2]);
---------------

Generic Collections in .NET

What are different types of collections in .NET?

There are five important collections in .NET Arrays, Lists, Hashtable, stacks and queues.

What are hashtable collections?

In arraylist or array if we have to access any data we need to use the internal index id generated by the array list collection. For instance the below code snippet shows how the internal id is used to fetch data from array list.

In actual scenarios we hardly remember internal id’s generated by collection we would like to fetch the data by using some application defined key. There’s where hash table comes in to picture.

string str = MyList[1].ToString();

Hash table helps to locate data using keys as shown below. When we add data to hash table it also has a provision where we can add key with the data. This key will help us to fetch data later using key rather than using internal index id’s generated by collections.

objHashtable.Add(“p001”,”MyData”);

This key is converted in to numeric hash value which is mapped with the key for quick lookup.

What are Queues and stack collection?

Queues are collection which helps us to add object and retrieve them in the manner they were added. In other word queues helps us to achieve the first in first out collection behavior.

Stack collection helps us to achieve first in last out behavior.

Can you explain the concept of generic collection?

Array List, Stack and Queues provide collections which are not type safe. This leads 2 problems first it’s not type safe and second it leads to boxing and unboxing.

By using generics we can have type safety and also we can avoid boxing and unboxing. Below is a simple code snippet which shows a strong typed list of type integer and string.

List<int> obj;
obj.add(1); // you can only add integers to this list
List<string> obj;
obj.add(“shiv”); // you can only add string to this list
--------------
What are abstract classes?

Abstract class is a half defined parent class. The full implementation of abstract class is defined by the child classes.

For example below code snippet shows a simple abstract class / half defined class called “DatabaseCommon” and later the concrete classes i.e. “SQLServer” and “Oracle” inherit and define a complete implementation for the same.

To define an abstract class we need to use the abstract keyword.

public abstract class DatabaseCommon
{
}
public  class SQLServer : DatabaseCommon
{
}
public  class Oracle : DatabaseCommon
{
}

What are abstract methods?

Abstract classes can have abstract methods. Abstract methods when defined in a parent class have to be implemented in the child classes. If abstract methods are not implemented it will throw a error.

An abstract with only abstract method, how is it different from interfaces?

If you define all methods, function, properties as abstract in abstract class it inhibits the same behavior as an interface.

Can we create an object of abstract class or an interface?

No.
----------------
How is inheritance implemented in .NET?

Inheritance is implemented by using the “:” symbol.

Below is a simple code snippet where we have “Customer” class which is the parent class. We have then created a child class called as “CustomerDiscount” which inherits all the properties and adds a “Discount” property.

class Customer
{
public string customerName;
public string customerCode;
}

class CustomerDiscount : Customer
{
public double Discount;
}

How can we implement static polymorphism?

Static polymorphism is implemented by using method overloading. In compile time itself we come to know if there are mismatches. Below code snippet shows how method overloading is implemented. The add method can take either 2 inputs or 3 inputs.

Depending on the number of inputs the addition logic is executed.

// add method with 2 inputs.
objmaths.add(1,2);
// add method with 3 inputs.
objmaths.add(1,2,3);

How can we implement dynamic polymorphism?

Dynamic polymorphism is implemented by using overriding and virtual keyword.

Below is a simple code snippet which has three classes, Customer class is the parent class.CustomerDiscount10Percent and CustomerDiscount20Percent are child classes.

Customer parent class has a discount function which returns zero discounts. This function is defined as virtual and then overridden by both the child classes with 10 and 20% discount.

class Customer
{
public string customerName;
public string customerCode;
public  virtual int Discount()
{
return 0;
}
}

class CustomerDiscount10Percent : Customer
{
public  override int Discount()
{
return 10;
}

}

class CustomerDiscount20Percent : Customer
{
public  override int Discount()
{
return 20;
}

}

Now on the client side on the fly your parent object can point to any child classes and invoke the child implementation accordingly. This is called as dynamic polymorphism; the parent object can point to any of the child objects and invoke the child function dynamically.

Customer obj;
obj = new CustomerDiscount10Percent();
obj = new CustomerDiscount20Percent();
-------------------

No comments:

Post a Comment