Monday, 19 August 2019

Questions For Interview



What is the difference between DLL and EXE files?
DLL (Dynamic Link Library)
EXE
It Doesn’t contain Main method.
It will contain Main method.
Cannot run individually
Can run individually.
Used as a supportive file for other applications.
Never used as a supportive file
OS doesn’t create separate process for any DLL   rather DLL will run in the same process created for an Exe.
OS creates a separate process for each Exe it’s executes.
A Program/application without Main method creates a DLL after compilation.
A Program/application with Main method creates the after compilition

What is Value Type and Reference Type?
Value Type
Reference Type
The data type which can store the data directly into their memory locations are known as Value type.
The data type which can store the data directly into their memory locations rather refer to other memory location where data is stored are known as reference type.
Memory is allocated at Compiler time.
Memory is allocated at Run time.
Memory allocation is made with in the stack i.e in continuous memory location.
Memory allocation is made with in the heap i.e in random memory location.
CLR doesn’t provide automatic memory management.
CLR provide automatic memory management.
Occupies less memory.
Occupies more memory.
If data is not initialized, then stores the default value in to the variable.
Ex:- int a; a=10
If data is not initialized, then stores the default value in to the reference.
Ex:- String.s=”Satya”

What are Console.ReadLine, Console.Read and Console.ReadKey?
1. Console.ReadLine(): A static method which accepts the String and return the string as well.
ReadLine (returns a string): reads only single line from the standard input stream.
Example: - It can be used to ask the user enter their name or age.
2. Console.Read(): A static method which accepts the String but returns an Integer.
Read (returns an int): reads only one single character from the standard input stream. Similar to ReadKey except that it returns an integer.
3. Console.ReadKey(): A static method which accepts the Character and return ASCII value of that character. 
ReadKey (returns a character): reads only one single character from the standard input stream.

What are Write and WriteLine?
The Write () method outputs one or more values to the screen without a new line character. TheWriteLine() always appends a new line character to the end of the string. This means any subsequent output will start on a new line.

What are an ExecuteScalar, ExecuteReader and ExecuteNonQuery?
ExecuteScalar is typically used when your query returns a single value. If it returns more, then the result is the first column of the first row. An example might be SELECT @@IDENTITY AS 'Identity'.
ExecuteReader : ExecuteReader used for getting the query results as a DataReader object. It is readonly forward only retrieval of records and it uses select command to read through the table from the first to the last.
  SqlDataReader reader;
  reader = Command.ExecuteReader();
  while (reader.Read()) {
               MessageBox.Show(reader.Item(0));
  }
  reader.Close();

ExecuteNonQuery : ExecuteNonQuery used for executing queries that does not return any data. It is used to execute the sql statements like update, insert, delete etc. ExecuteNonQuery executes the command and returns the number of rows affected.
  int retValue = 0;
  Command = new SqlCommand(Sql, Connection);

  retValue = Command.ExecuteNonQuery();

What is a Managed and Un-managed code?
Managed Code:- Code that executes under CLR execution environment is called as Managed code.
Unmanaged Code:- Code that get executes outside CLR boundary.

What is an assembly and types of assemblies?
Assembly is a unit of deployment like EXE or a DLL.
Types of assembly: - There are two types of assemblies
1) Private assembly: - It is normally used by a single application, and is stored in the application’s directory.
2) Public or Shared assembly: It is stored in the global assembly cache, which is a repository of assemblies maintained by the .net runtime.

What is boxing and Un-boxing?
Whenever a value type member is assigned to the reference type member it’s called as boxing.
Whenever a reference type member is assigned to the value type member it’s called as Un-boxing.
class Test
{
static void Main()
{
int i = 1;
object o = i; // boxing
int j = (int) o; // unboxing
}
}

What are Generics?
Generics help to separate logic and data type to increase re-usability. In other words you can create a class whose data type can be defined on run-time.

What is variable and dynamic keyword?
Var:-
Introduced in C#3.0
Statically typed – This means the type of variable declared is decided by the compiler at compile time.
Dynamic:-
Introduced in C# 4.0
Dynamically typed - This means the type of variable declared is decided by the compiler at runtime time.

What is Static, Void, Main and String[] args?
Static: is a keyword which means object is not required to access static members. So it saves memory. (or) To use static main method can be called without creating an object of the class.
Void: It doesn’t return any value. In such case, return statement is not required.
Main: is the method name. It is the entry point for any C# program. Whenever we run the C# program, Main () method is invoked first before any other method. It represents startup of the program.
String [] args: is used for command line arguments in C#. While running the C# program, we can pass values. These values are known as arguments which we can use in the program.

What is Object Oriented Programming?
OOP is software designing technique where we think in terms of real world objects.

What is Class?
A class is a collection of method and variables.
A class defines certain properties, fields, events, method etc.
A class enables you to create your own custom types by grouping together variables of other types, methods and events.
A class can be defined by using the class keyword.

What is a Namespace?
A namespace is an abstract container or environment created to hold a logical grouping of unique identifiers (i.e names).
Namespaces allow to group entities like classes, objects and functions under a name.

What are Abstraction, Encapsulation, Inheritance and Polymorphism?
Abstraction:
Abstraction is a process of hiding the unwanted data and giving only relevant data.
Abstraction solves the problem in the design level.
Encapsulation:
Encapsulation is a process of binding the data members and member functions into a single unit.
Encapsulation solves the problem in the implementation level.
Inheritance:
Inheritance is a process of deriving / creating a new class from an existing class.
Main purpose of inheritance is code Re-usability and providing additional functionality / enhancement.
Polymorphism:
It is a property of object to act differently under different conditions.
Types of Polymorphism: -
1) Static Polymorphism / Compile time Polymorphism / Early Binding.
It is implemented by using method overloading. In compile time itself we come to know if there are mismatches.
2) Dynamic Polymorphism / Run time Polymorphism / Late Binding.
It is implemented by using override and virtual keyword.

What are different access modifiers?
There are total 5 access modifiers
Private: Only members of class have access to the variables.
Protected: All members in current class and in derived classes can access the variables.
Friend (Internal in C#): Only members in current project have access to the elements.
Protected friend (Protected internal in C#): All members in current project and all members in derived class can access the variables.
Public: All members have access in all classes and projects.

What is Abstraction and Encapsulation?
Abstraction is design process while Encapsulation happens during phase which is achieved by using access modifiers.
Abstraction is done in design phase while Encapsulation is implemented in execution phase using access modifiers.

What is the difference between Overloading and Overriding?
Overloading: where we can have same method names with different input signature.
Overriding: we have a parent class with virtual functions which are overridden in the child classes.

What is abstract class?
Abstract class is a half-defined parent class. The full implementation of abstract class is defined by the child classes.
To define an abstract class we need to use the abstract keyword.

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.

What is Delegate? And types of Delegates?
Delegate is an abstract pointer to a function or method. In other words you can create a pointer which points to a method or function and then pass that pointer wherever you wish and invoke the function/method.

Delegates are used in the following cases:
Delegates can be used to handle (call/invoke) multiple methods on a single event.
Delegates can be used to define callback (asynchronous) methods.
Delegates can be used for decoupling and implementing generic behaviors.
Delegates can be invoked method at runtime.
Delegates can be used in LINQ for parsing the Expression Tree.
Delegates can be used in different Design Pattern.

Types of Delegates
There are three types of delegates that can be used in C#.
       Single Delegate
 Multicast Delegate
 Generic Delegate
   1. Func
   2. Action
   3. Predicate

What is the difference between Class and Structure?
Class
Structure
Classes are reference types.
Structures are value types.
Classes use in heap.
Structures use in stack.
Class members can be declared as protected.
Structures members cannot be declared as protected.
Classes require Constructors.
Structures do not require Constructors.
Objects created from classes are terminated using Garbage Collector (GC).
Structures are not destroyed using Garbage Collector (GC).

What is sealed Class in C#?
Sealed class is used to prevent the class from being inherited from other classes.

What is method overloading?  
Method overloading is creating multiple methods with the same name with unique signatures in the same class. When we compile, the compiler uses overload resolution to determine the specific method to be invoke.

What is the difference between method overriding and method overloading?
In method overriding, we change the method definition in the derived class that changes the method behavior.

Method overloading is creating a method with the same name within the same class having different signatures.
e.g
public class Methodoveloading    
  {    
    public int add(int a, int b)  //two int type Parameters method  
    {    
        return a + b;      
    }    
    public int add(int a, int b,int c)  //three int type Parameters with same method same as above  
    {    
        return a + b+c;     
    }    
    public float add(float a, float b,float c,float d)  //four float type Parameters with same method same as above two method
    {
       return a + b+c+d;    
    }    
  }    

What is the difference between “Constant” and “Read only” variables in C#?
“Constant” keyword is used for making an entity constant. We cannot modify the value later in the code. Value assigning is mandatory to constant variables.
“Read only” variable value can be changed during run time and value to read only variables can be assigned in the constructor or at the time of declaration.

What is the difference between “Out” and “Ref” parameters in C#?
“Out” parameter can be passed to a method and it need not be initialized where as “ref” parameter has to be initialized before it is used.
Ref Parameter: -
If you want to pass a variable as ref parameter you need to initialize it before you pass it as ref parameter to method. Ref keyword will pass parameter as a reference this means when the value of parameter is changed in called method it get reflected in calling method also.
Out Parameter: -
If you want to pass a variable as out parameter you don’t need to initialize it before you pass it as out parameter to method. Out keyword also will pass parameter as a reference but here out parameter must be initialized in called method before it return value to calling method.

What is the difference between “String” and “String Builder”?
String
String Builder
It’s an immutable (Immutable means when you will create a string type object, then you cannot modify it in memory. If you will modify it, then it will create a new instance of the object in memory.)
It’s mutable(It means you can modify the String Builder object without creating new instances in memory.)
Performance wise string is slow because every time it will create new instance
Performance wise string builder is high because it will use same instance of object to perform any action
In string we don’t have append keyword
In String Builder we can use append keyword
String belongs to System namespace
String builder belongs to System.Text namespace.

What is Serialization and De-serialization?
The process of converting an object into a stream of bytes is called Serialization.
De-serialization is the reverse process of creating an object from a stream of bytes.

Define Constructors?  
A constructor is a member function in a class that has the same name as its class. The constructor is automatically invoked whenever an object class is created. It constructs the values of data members while initializing the class.

Constructor is used to initialize an object (instance) of a class.
Constructor is a like a method without any return type.
Constructor has same name as class name.
Constructor follows the access scope (Can be private, protected, public, Internal and external).
Constructor can be overloaded.

Constructors generally following types:
Default Constructor
Parameterized constructor
Private Constructor
Static Constructor
Copy Constructor

What is the difference between “Convert.ToString ()”and “.ToString ()” methods?
Example: - int i=0;
                   MessageBox.Show(i.ToString());
                   MessageBox.Show(Convert.ToString(i));
We can convert the integer “i” using “i.ToString()” or “Convert.ToString” so what is the difference. The basic difference between them is “Convert” function which handles Nulls while “i.ToString()” does not do. It will throw a Null referencing exception error. So as a good coding practice using “Convert” is always safe.

What is the difference between “Enumeration” and “Enum”?
Enumeration: - An enumeration is used in any programming language to define a constant set of values. The enumeration is defined with the help of the keyword 'enum'.

Enum: - Is a value type data type. In other words, enumeration contains its own values and cannot inherit or cannot pass inheritance.
The enum is used to declare a list of named integer constants using the enum keyword directly inside a namespace, class, or structure.
The enum is used to give a name to each constant so that the constant integer can be referred using its name.

What is the difference between “Dictionary” and “Hash table”?
Dictionary collection is a generic collection equivalent for hash table.
Hash table allows you to add key and value of any type (i.e., Objects). This leads to two problems one is boxing and unboxing issues and second it’s not strongly typed.

What is the use of IEnumerable, ICollection and IDictionary?
IEnumerable: - All collection classes use this interface and it helps to iterate through all the collection elements.
ICollection: - This interface has the count property and it is implemented by all collection elements.
IDictionary: - This interface is implemented by hash table and dictionary.

What is IEnumerable and IQuerable?
IEnumerable: - It is suitable just for iterate through collection and you can not modify (Add or Remove) data IEnumerable bring ALL data from server to client then filter them, assume that you have a lot of records so IEnumerable puts overhead on your memory.

·    IQuerable: - Whenever we encounter to huge data with so many records so we have to reduce overhead from application. IQueryable prepares high performance in such situations (huge data) by filtering data firstly and then sending filtered data to client.
IEnumerable
IQueryable
IEnumerable exists in System.Collections Namespace.
IQueryable exists in System. Linq Namespace.
IEnumerable doesn’t support custom query.
IQueryable supports custom query using CreateQuery and Execute methods.
IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.
IQueryable support lazy loading. Hence it is suitable for paging like scenarios.
IEnumerable supports deferred execution.
IQueryable supports deferred execution.
IEnumerable is suitable for LINQ to Object and LINQ to XML queries.
IQueryable is suitable for LINQ to SQL queries.
IEnumerable can move forward only over a collection, it can’t move backward and between the items.
IQueryable can move forward only over a collection, it can’t move backward and between the items.

What are the Custom controls and User controls?
Custom Control: - A custom control is the one which is made or created by the programmer to serve the business needs, by extending the functionality of existing controls. 

User Control: - User controls are created just like a web form. They make use of the existing controls to define their own logic.

Custom Control
User Control
A loosely coupled control w.r.t code and UI
A tightly coupled control w.r.t code and UI
Derives from Control
Derives from UserControl
Defines UI in a ResourceDictionary
Defines UI as normal XAML
UI is skinable
Child controls are skinable
Defines a single control
Defines a set of controls
More flexible
Not very flexible like a Custom Control
Requires in-depth knowledge of Silverlight UI Model
Does not require in-depth knowledge of the UI Model

User Control:-
1. Reusability Webpage.
2. We can’t add to toolbox.
3. Just drag and drop from solution explorer to page (aspx).
4. U can register user control to Aspx page by Register tag.
5. A separate copy of the control is required in each application.
6. Good for static layout.
7. Easier to create.
8. Not complied into DLL (Do not run on their own dll).

Custom Controls:-
1. Reusability of control (or extend functionalities of existing control).
2. We can add toolbox.
3. Just drag and drop from toolbox.
4. U can register user control to Aspx page by Register tag.
5. A single copy of the control is required in each application.
6. Good for dynamic layout.
7. Hard to create.

8. Complied in to DLL (Run on their own dll).

What are the Local and Global resources?
Local Resources
Global Resources
Page-Specific
Can be read from any page within the website.
Can be used only in the specific page.
Define resource file once and share it across the website
.resx file
.resx file
Same convention to name the file as per the language and culture.
Same convention to name the file as per the language and culture.
Stored in the App_LocalResources folder
Stored in the App_GlobalResources folder.
App_LocalResources folder can be present either in root folder or in subfolders
App_GlobalResources folder must be present in the root of the application.
Can be used implicitly or explicitly in the markup
Must be used explicitly
Does not generate any object.
Generates an object for the Global Resource file to be used in the code to access the resource values.


What is an Array and Array List?
The following table lists the difference between Array and Array List in C#.

Array
Array List
Array is strongly typed. This means that an array can store only specific type of items\elements.
Array List can store any type of items\elements.
Array stores fixed number of elements. Size of an Array must be specified at the time of initialization.
Array List grows automatically and you don't need to specify size.
No need to cast elements of an array while retrieving because it is strongly type and stores specific type of items only.
Items of Array List need to be cast to appropriate data type while retrieving.
Use static helper class Array to perform different tasks on the array.
Array List itself includes various utility methods for various tasks.

What is Stack and Heap?
Stack memory stores data types like int, double, Boolean, etc.,
Heap stores data types like string and objects.
Ex: - int i=1; // This is stored in stack.
       int y=i; // This is stored in stack.
       object o=null; // This is stored in heap.

What is difference between Abstract class and Interface?
Abstract Class
Interface
Abstract classes are used when we want to share common functionality in parent-child relationship.
Interfaces are used to define contract, enforce standardization, decoupling and dynamic polymorphism.
Some methods in abstract classes can have implementation.
All methods, function, properties in interfaces have to empty compulsorily.
We can declare variables.
We cannot declare variables.
Abstract classes are inherited.
Interfaces are implemented.


ASP.NET Questions

What is grid view code?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
            <Columns>
                 <asp:BoundField DataField = "Name" HeaderText = "Name" />
                <asp:BoundField DataField = "password" HeaderText = "password" />
                <asp:TemplateField>
                  <ItemTemplate>
          <asp:Image ID="Image1" runat="server" ImageUrl='<%#Eval("image")%>' Height = "100" Width = "100" />
        </ItemTemplate>
   </asp:TemplateField>             
             </Columns>            
        </asp:GridView>


{
  con.Open();
SqlCommand cmd = new SqlCommand("select * from Filling  where Username='"+txtUsername.Text+"'", con);
       SqlDataAdapter da = new SqlDataAdapter(cmd);
       DataSet ds = new DataSet();
       da.Fill(ds);
       GridView1.DataSource = ds.Tables[0];
       GridView1.DataBind();
       con.Close();

What are the Asp.Net page life cycle events?
At each stage of the page life cycle, the page raises some events, which could be coded. An event handler is basically a function or subroutine, bound to the event, using declarative attributes such as Onclick or handle.

Following are the page life cycle events:
ü  PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and determines whether the page is a postback. It sets the themes and master pages, creates dynamic controls, and gets and sets profile property values. This event can be handled by overloading the OnPre-Init method or creating a Page_PreInit handler.
ü  Init - Init event initializes the control property and the control tree is built. This event can be handled by overloading the OnInit method or creating a Page_Init handler.
ü  InitComplete - InitComplete event allows tracking of view state. All the controls turn on view-state tracking.
ü  LoadViewState - LoadViewState event allows loading view state information into the controls.
ü  LoadPostData - During this phase, the contents of all the input fields are defined with the <form> tag are processed.
ü  PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event can be handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
ü  Load - The Load event is raised for the page first and then recursively for all child controls. The controls in the control tree are created. This event can be handled by overloading the OnLoad method or creating a Page_Load handler.
ü  LoadComplete - The loading process is completed, control event handlers are run, and page validation takes place. This event can be handled by overloading the OnLoadComplete method or creating a Page_LoadComplete handler.
ü  PreRender - The PreRender event occurs just before the output is rendered. By handling this event, pages and controls can perform any updates before the output is rendered.
ü  PreRenderComplete - As the PreRender event is recursively fired for all child controls, this event ensures the completion of the pre-rendering phase.
ü  SaveStateComplete - State of control on the page is saved. Personalization, control state and view state information is saved. The HTML markup is generated. This stage can be handled by overriding the Render method or creating a Page_Render handler.
ü  UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all controls recursively and lastly for the page itself. Final cleanup is done and all resources and references, such as database connections, are freed. This event can be handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

Describe the complete lifecycle of a Web page?
When we execute a Web page, it passes from the following stages, which are collectively known as webpage lifecycle:
Page request - During this stage, ASP.NET makes sure the page either parsed or compiled and a cached version of the page can be sent in response
Start - During this stage sets the Request and Response page properties and the page check the page request is either a post back or a new request
Page Initialization - During this stage, the page initialize and the control's Unique Id property are set
Load - During this stage, if the request is post back, the control properties are loaded without loading the view state and control state otherwise loads the view state
Validation - During this stage, the controls are validated
Post back event handling - During this stage, if the request is a post back, handles the event
Rendering - During this stage, the page invokes the Render method to each control for return the output
Unload - During this stage, when the page is completely rendered and sent to the client, the page is unloaded.

What are Http Handlers and Http Modules?
Handlers and Modules help you inject pre-processing logic before the asp.net request reaches the website.
“HTTP Handlers” is an extension-based processor. In other words the pre-processing logic is invoked depending on file extensions.
“HTTP Module” is an event-based processor. In other words Asp.Net emits a lot of events like begin Request, Authentication Request, etc., We can write logic in those events using HTTP Module.

What is the use of Global.asax?
The Global.asax, also known as the ASP.NET application file, is used to serve application-level and session-level events. 

What are major events in Global.asax file?
Global.asax is an optional file which is used to handling higher level application events such as 
·         Application_Start
·         Application_End
·         Session_Start
·         Session_End
·         Application_BeginRequest
·         Application_AuthenticateRequest
·         Application_Error
It is also popularly known as ASP.NET Application File. This file resides in the root directory of an ASP.NET-based application

What is "Server.Transfer" and "Response.Redirect"?
“Response.Redirect” and “Server.Transfer” helps to transfer user from one page to other page while executing the page.
The main difference between them is who does the transfer. In “Response.Redirect” the transfer is done by the browser while in “Server.Transfer” it’s done by the server.
“Server.Transfer” when you want to navigate pages which reside on the same server.
“Response.Redirect” when you want to navigate between pages which resides on different server and domain.

What are the Server side and Client side controls?
Client Side Controls: - 
1) Client side refers to the browser which is viewing the web page delivered by the server. This is HTML and JavaScript, maybe Shockwave flash, maybe Silverlight. 
2) Request the page, receive the page from the server, then display the HTML and process the JavaScript. 
3) The client side validation can be done using the JavaScript or vb script. 
4) Client side validation is processed the client side before submitting the form. The advantage of using the client side validation is it reduces the network traffic since the validation is processed in the client machine itself. 

Server Side Controls:-
1) Server side refers to the application on the web server which delivers the web page content.
2) Create and deliver the HTML and JavaScript
3) login and password must be validate at server side.

What is the difference between authentication and authorization?
Authentication is verifying the identity of a user and authorization is process where we check does this identity have access rights to the system. Authorization is the process of allowing an authenticated user access to resources.
(Or)
When you log on to a PC with a user name and password you are authenticating. Authorization is the process of verifying that you have access to something. Gaining access to a resource (e.g. directory on a hard disk) because the permissions configured on it allow you access is authorization.

How do i send email message from Asp.net?
Mail Message to build the actual email message to be sent and SmtpClient to do the actual sending.
Now, the Web.config file needs to be updated so the server knows your email account credentials.
Add this code to your Web.config file before the final </configuration> tag:
<system.net>
  <mailSettings>
    <smtp>
      <network defaultCredentials="false"
           host="mail.yourdomain.com" port="25"
           userName="name-to-send-email@yourdomain.com"
           password="*****"/>
     </smtp>
   </mailSettings>
</system.net>
To implement this mail concept in your asp.net application first we need to add this reference to our application System.Web.Mail namespace

What is System.Net.Mail
The System.Net.Mail namespace contains classes used to send electronic mail to a Simple Mail Transfer Protocol (SMTP) server for delivery.
How we can get this reference (System.Net.Mail)

What is Link button Control and Hyperlink Controls?
Hyperlink control:
              It is immediately navigates to the target URL when the user clicks on the control. The form is not posted to the server.
LinkButton:
             It is first posts the form to the server, and then navigates to the URL. If you need to do any server side processing before going to the target URL.

What is cross page posting?
Cross-page posting means that you are posting form data to another page as opposed to posting form data back to the same page (as is the default in ASP.NET). ... By default, buttons and other controls that cause a post back on an ASP.NET Web page submit the page back to itself.
Cross page posting is the concept which is used to submit one page (Default.aspx) controls to another page (Default2.aspx) and access those page (Default.aspx) control values in another page (Default2.aspx).
ASP.NET by default submit the forms to the same pages, Cross-page posting is submitted the form to a different page. This is usually required when you are creating a multipage form to collect information from the user on each page. When moving from the source to the target page.
“To use cross-page posting, you have to use the ‘postBackUrl’ attribute to specify the page we want to post.”

What are the different types of validation controls in Asp.net?
There are six types of validation controls in ASP.NET
1. RequiredFieldValidation Control
2. CompareValidator Control
3. RangeValidator Control
4. RegularExpressionValidator Control
5. CustomValidator Control
6. ValidationSummary

What are the different levels of State management in ASP.NET?
State management is the process by which you maintain state and page information over multiple requests for the same or different pages.

There are 2 types State Management:

1.Client– Side StateManagement
This stores information on the client's computer by embedding the information into a Web page, a uniform resource locator (url), or a cookie. The techniques available to store the state information at the client end are listed down below:

a. View State – Asp.Net uses View State to track the values in the Controls. You can add custom values to the view state. It is used by the Asp.net page framework to automatically save the values of the page and of each control just prior to rendering to the page. When the page is posted, one of the first tasks performed by page processing is to restore view state.

b. Control State – If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state.

c. Hidden fields – Like view state, hidden fields store data in an HTML form without displaying it in the user's browser. The data is available only when the form is processed.

d. Cookies – Cookies store a value in the user's browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on a web site.

e. Query Strings - Query strings store values in the URL that are visible to the user. Use query strings when you want a user to be able to e-mail or instant message state data with a URL.

2. Server – Side State Management
a. Application State - Application State information is available to all pages, regardless of which user requests a page.

b. Session State – Session State information is available to all pages opened by a user during a single visit.

Both application state and session state information is lost when the application restarts. To persist user data between application restarts, you can store it using profile properties.

What is State Management? How many ways are there to maintain a state in .NET?
State management is used to store information requests. The state management is used to trace the information or data that affect the state of the applications.

There are two ways to maintain a state in .NET, Client-Based state management and Server-Based state management.

The following techniques can be used to implement the Client-Based state management:
1.      View State
2.      Hidden Fields
3.      Cookies
4.      Query Strings
5.      Control State

The following techniques can be used to implement Server-Based state management:


1.      Application State
2.      Session State
3.      Profile Properties
  
What are session state modes in Asp.net?
ASP.NET session state supports several different storage options for session data. Each option is identified by a value in the Session State Mode enumeration. The following list describes the available session state modes:

1.      InProc mode, which stores session state in memory on the Web server. This is the default.
2.      StateServer mode, which stores session state in a separate process called the ASP.NET state service. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
3.      SQLServer mode stores session state in a SQL Server database. This ensures that session state is preserved if the Web application is restarted and also makes session state available to multiple Web servers in a Web farm.
4.      Custom mode, which enables you to specify a custom storage provider.
5.      Off mode, this disables session state.

What is a ViewState?
The ViewState is a feature used by ASP.NET Web page to store the value of a page and its controls just before posting the page. Once the page is posted, the first task by the page processing is to restore the ViewState to get the values of the controls.

What is a Cookie? Where is it used in ASP.NET?
Cookie is a lightweight executable program, which the server posts to client machines. Cookies store the identity of a user at the first visit of the Web site and validate them later on the next visits for their authenticity. The values of a cookie can be transferred between the user's request and the server's response.

How many types of Cookies are available in ASP.NET?
There are two types of Cookies available in ASP.NET:

1.      Session Cookie - Resides on the client machine for a single session until the user does not log out.

2.      Persistent Cookie - Resides on a user's machine for a period specified for its expiry, such as 10 days, one month, and never.

Explain how Cookies work. Give an example of Cookie abuse?
The server tells the browser to put some files in a cookie, and the client then sends all the cookies for the domain in each request. An example of cookie abuse is large cookies affecting the network traffic.

What is the difference between Application state and Session?
The Difference between Session state and Application state is
 i) Session state is about particular user which is available in every page of site.
ii) Application state is Available to every user in every page of the site.

What are the difference between “Data set” and “Data Reader”?
Data set
Data Reader
“Data set” is a disconnected architecture.
“Data reader” is connected architecture.
“Data set” moves back as well as forward.
“Data reader” provides forward-only and read-only access.
“Data set” object is an in-memory database with tables, rows and columns.
“Data reader” is just simple table which can be read only in a forward direction.
“Data set” can manipulate data.
“Data reader” is only for reading purpose.

SQL SERVER Questions

Explain DML and DDL?
DML stands for Data Manipulation Language. INSERT, UPDATE and DELETE are DML statements.
DDL stands for Data Definition Language. CREATE, ALTER, DROP, RENAME are DDL statements.

What is the difference between unique key and primary key?
Primary key
Unique key
Primary key doesn’t allow null values.
Unique key allows null value (although only one).
There can be only one primary key.
A table can have more than one unique key column.
Primary key creates a clustered index on the column.
Unique key column creates non-clustered index.
A Primary key is column
Uniquely identify every row in a table.

What is the difference between Functions and Stored procedures?
Stored Procedures
Functions
Stored procedure can return Zero or n values.
Function can return one value.
Stored procedures can have input and output parameters.
Functions can have only input parameters.
Stored procedure allows select as well as DML statement in it.
Function allows only select statement in it.
Stored procedures cannot be called from function.
Functions can be called from stored procedure.

Exception can be handled by try-catch block in a procedure.

Try-catch block cannot be used in a function.
We can go for transaction management in procedure 
We can't go in function.
Stored procedures cannot be utilized in a select statement.
Function can be embedded in a select statement.

What are the differences between TRUNCATE vs DELETE?
TRUNCATE
DELETE
TRUNCATE is a DDL command
DELETE is a DML command
TRUNCATE is executed using a table lock and whole table is locked for remove all records.
DELETE is executed using a row lock; each row in the table is locked for deletion.
We cannot use Where clause with TRUNCATE.
We can use where clause with DELETE to filter & delete specific records.
TRUNCATE removes all rows from a table.
The DELETE command is used to remove rows from a table based on WHERE condition.
Minimal logging in transaction log, so it is performance wise faster.
It maintain the log, so it slower than TRUNCATE.
TRUNCATE TABLE removes the data by de-allocating the data pages used to store the table data and records only the page de-allocations in the transaction log.
The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row
Identify column is reset to its seed value if table contains any identity column.
Identity of column keep DELETE retain the identity
To use Truncate on a table you need at least ALTER permission on the table.
To use Delete you need DELETE permission on the table.
Truncate uses the less transaction space than Delete statement.
Delete uses the more transaction space than Truncate statement.
Truncate cannot be used with indexed views
Delete can be used with indexed views
Drop all object’s statistics and marks like High Water Mark free extents and leave the object really empty with the first extent. zero pages are left in the table
Keeps object’s statistics and all allocated space. After a DELETE statement is executed, the table can still contain empty pages.
TRUNCATE TABLE can’t activate a trigger because the operation does not log individual row deletions. When we run truncate command to remove all rows of table then it actually doesn’t removes any row, rather it de-allocates the data pages. In case of Truncate triggers will not be fired because no modification takes place, we have just de-allocated the data pages not deleted any row from table.
Delete activates a trigger because the operations are logged individually. When we execute Delete command, DELETE trigger will be initiated if present. Delete is a DML command and it deletes the data on row-by-row basis from a table. Which means delete is modifying the data by deleting it from the table. Triggers are fired when a DML statement executed on a table, so trigger will be fired in case of Delete command execution.

What is a Clustered Index?

Clustered indexes physically sort the rows in the table based on the clustering key (by default primary key). Clustered index helps in fast retrieval of data from the databases. There can be only one clustered index in a table.

What is a Non-clustered index?
Non clustered indexes have a jump table containing key-values pointing to row in the table corresponding to the keys. There can be multiple clustered indexes in a table.

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?
a.       One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships.
b.      One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships.
c.       Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table.

 Write a query select top 5 salary from employee table?

SELECT TOP 5 Salary   FROM  EmployeeTable   ORDER BY Salary DESC

What is a transaction?
A transaction is a sequence of code that runs against a database. It takes database from one consistent state to another.

Define a temp table?
A temp table is a temporary storage structure to store the data temporarily.

What is Trigger and How many types of triggers?
Trigger allows us to execute a batch of SQL code when a table event occurs (Insert, update or delete command executed against a specific table).

What is View?
A view contains rows and columns, just like a real table. The fields in a view are fields from one or more real tables in the database.
(Or)
A view is a virtual table which contains data from one or more tables. Views restrict data access of table by selecting only required values and make complex queries easy. Rows updated or deleted in the view are updated or deleted in the table the view was created with. It should also be noted that as data in the original table changes, so does data in the view, as views are the way to look at part of the original table. The results of using a view are not permanently stored in the database.

List out the different types of locks available in Sql Server?
Below are the lists of locks available in Sql Server –
1.      Update Locks
2.      Shared Locks
3.      Exclusive Locks

Why to use “No Lock” in Sql Server?
“No Lock” is used for unlocking the rows which are locked by some other transaction. Once after the rows are committed or rolled back no need to use No Lock. For example
SELECT * from Employees WITH (NOLOCK)

ASP.NET MVC Questions

What is the difference between Asp.net Web form and Asp.net MVC?
ASP.NET web forms
ASP.NET MVC
Asp.Net Web form has file-based URLs means file name exist in the URLs must have its physically existence.
Asp.Net MVC has route-based URLs means URLs are divided into controllers and actions and moreover it is based on controller not on physical file.
Asp.Net Web form has User Controls for code re-usability.
Asp.Net MVC has Partial views for code re-usability.
Asp.Net Web form supports view state for state management at client side.
Asp.Net MVC does not support View state.
Asp.Net Web forms has Master pages for consistent look and feels.
Asp.Net MVC has layouts for consistent look and feels.
Asp.Net Web form has every page has its own controller, i.e., code-behind file that processes the request.
Asp.Net MVC has common controller for all pages processes the requests.
It’s good for small scale applications.
It’s better as well as recommended approach for large-scale applications.
Test driven development is not using.
Test driven development is quite simple using this approach.

Explain the page life cycle of MVC?
Below are the processed followed in the sequence -
1.      App initialization 
2.      Routing 
3.      Instantiate and execute controller 
4.      Locate and invoke controller action 
5.      Instantiate and render view.

 Explain what are the steps for the execution of an MVC project?
The steps for the execution of an MVC project includes
1. Receive first request for the application
2. Performs routing
3. Creates MVC request handler
4. Create Controller
5. Execute Controller
6. Invoke action
7. Execute Result

What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”?
Both of them provide the same HTML output, “HTML.TextBoxFor” is strongly typed while “HTML.TextBox” isn’t. Below is a simple HTML code which just creates a simple textbox with “CustomerCode” as name.
Html.TextBox("CustomerCode")

Below is “Html.TextBoxFor” code which creates HTML textbox using the property name ‘CustomerCode” from object “m”.
Html.TextBoxFor(m => m.CustomerCode)

In the same way we have for other HTML controls like for checkbox we have “Html.CheckBox” and “Html.CheckBoxFor”.

What are routing in MVC?
Routing helps you to define user friendly URL structure and map those URL structure to the controller. For instance let’s say we want that when any user types “http://localhost/View/ViewCustomer/”, it goes to the “Customer” Controller and invoke “DisplayCustomer” action.  This is defined by adding an entry in to the “routes” collection using the “maproute” function. Below is the under lined code which shows how the URL structure and mapping with controller and action is defined.
routes.MapRoute ("View", // Route name            
                              "View/ViewCustomer/{id}", // URL with parameters             
     new {controller="Customer", action="DisplayCustomer", id= UrlParameter.Optional }); // Parameter defaults

What is Filter?
Sometimes we would like to perform certain action before or after a particular operation, or sometimes we need a pre or post action behaviors from action, for achieving this functionality ASP.NET MVC provides a feature called Filters.

What are the different types of filters in Asp.net MVC?
ASP.NET MVC supports the following types of filters:
1.      Action Filters
2.      Authorization Filter
3.      Result Filter
4.      Exception Filter

(1)   Action Filter: - Action Filters are used to implement the logic that get executed before or after a controller action executes.
(2)   Authorization Filter: - It is used to implement authorization and authentication for action filters.
(3)   Result Filter: - Result filter contains logic that gets executed before or after a view result gets executed. E.g. If you want to change view before its get render to browser.
(4)   Exception Filter: - Exception filters are used to handle error, caused by either controller action or controller action results, we can also use it for logging the exceptions.


What are the Action Results in MVC?
There 12 kinds of results in MVC, at the top is “ActionResult” class which is a base class that can have 11 sub types as listed below:
1. ViewResult - Renders a specified view to the response stream
2. PartialViewResult - Renders a specified partial view to the response stream
3. EmptyResult - An empty response is returned
4. RedirectResult - Performs an HTTP redirection to a specified URL
5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
6. JsonResult - Serializes a given object to JSON format
7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
8. ContentResult - Writes content to the response stream without requiring a view
9. FileContentResult - Returns a file to the client
10. FileStreamResult - Returns a file to the client, which is provided by a Stream
11. FilePathResult - Returns a file to the client.

What are the Temp Data, View Data and View bag in Asp.net MVC?
Temp data: -Helps to maintain data when you move from one controller to other controller or from one action to other action. In other words when you redirect, “temp data” helps to maintain data between those redirects. It internally uses session variables.
View data: - Helps to maintain data when you move from controller to view.
 View Bag: - It’s a dynamic wrapper around view data. When you use “View bag” type casting is not required. It uses the dynamic keyword internally.

What is “peek” and “keep” in MVC?
Once “Temp Data” is read in the current request it’s not available in the subsequent request. If we want “Temp Data” to be read and also available in the subsequent request then after reading we need to call “Keep” method as shown in below code
@ Tempdata [“MyData”];
TempData.Keep (“MyData”);
The more shortcut way to achieving the same is by using “Peek”. This function helps to read as well advices MVC to maintain “TempData” for the subsequent request.
String str=TempData.Peek (“Td”).ToString();

What is the importance of Model Binders in MVC?
Accessing request values using the Request object is a cumbersome and time wasting activity. With model bindingMVC framework converts the http request values (from query string or form collection) to action method parameters. These parameters can be of primitive type or complex type.
Model Binding is the mechanism ASP.NET MVC uses to create strongly-typed objects (or fill primitive-type parameters) from the input stream (usually an HTTP request).

How many of the Data annotations in MVC?
When you use the Data Annotations Model Binder, you use validator attributes to perform validation. The “System.ComponentModel.DataAnnotations” namespace includes the following validator attributes:
Range – Enables you to validate whether the value of a property falls between a specified ranges of values.
Regular Expression – Enables you to validate whether the value of a property matches a specified regular expression pattern.
Required – Enables you to mark a property as required.
String Length – Enables you to specify a maximum length for a string property.
Validation – The base class for all validator attributes.
                                                     
What is the difference between View and Partial view?
View
Partial View
It contains the layout page.
It does not contain the layout page.
Before any view is rendered, view start page is rendered.
Partial view does not verify for a viewstart.cshtml. We cannot put common code for a partial view within the viewStart.cshtml page.
View might have markup tags like body, html, head, title, meta etc.
Partial view is designed specially to render within the view and just because of that it does not consist any mark up.
View is not lightweight as compare to Partial View.
We can pass a regular view to the Render Partial method.

What is Anti Forgery token Key?
The anti-forgery token can be used to help protect your application against cross-site request forgery. To use this feature, call the AntiForgeryToken method from a form and add the Validate AntiForgeryTokenAttribute attribute to the action method that you want to protect.

A great feature in ASP.NET MVC is the AntiForgeryToken. This generates a hidden form field (anti-forgery token) that is validated when the form is submitted. The anti-forgery token can be used to help protect your application against cross-site request forgery. To use this feature, all you need to do is add the following HTML helper to your form so it is submitted as part of the form post:
<%: Html.AntiForgeryToken() %>

This is great if you're running the page in an aspx page, but if you use a client template engine, such as jTemplates, you cannot use ASP.NET MVC syntax in a standard HTML page, but you still want to be able to get all the security goodness that comes with the AntiForgeryToken.

What is the difference between JavaScript and JQuery?

JavaScript
JQuery
JavaScript is a client-sided scripting language.
JQuery is simply a JavaScript library.
JavaScript is language and JavaScript is relatively simple to learn and implement.
JQuery is Framework.
JavaScript provide very interactive user interfaces and dynamic websites.
 is JQuery is designed to make many JavaScript development tasks much easier.
JavaScript is open and cross-platform.
JQuery is free, open source software.

What is Ajax?
AJAX = Asynchronous JavaScript and XML.
Ajax is method to use for exchanging data from client to server in asynchronously way without updating whole page.  

What are the methods of Ajax?
Ajax contains various methods those are:   
POST: This method is used for posting data to server side.     
GET: This method is used to get value from server to client.     
PUT: This method is used to update data value at server side.     
DELETE: This method is used to delete data value at server side.  
For working with Ajax we just requires JQuery library.

Write Ajax syntax?
varid=empid;
$.ajax({
    type: "POST",
    url: "../Webservices/EmployeeService.asmx/GetEmployeeOrders",
    data: "{empid: empid}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(result)
{
        alert(result.d);
    }
})

What is Dataset, Data reader and Data adapter?
Data Reader:-
// This method is used to bind gridview from database
protected void BindGridview()
{
using (SqlConnection con= new SqlConnection("DataSource=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName,LastName,Location FROM UserInformation", con);
SqlDataReader dr = cmd.ExecuteReader();
gvUserInfo.DataSource = dr;
gvUserInfo.DataBind();
con.Close();
}
}

Data set:-
// This method is used to bind grid view from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}

DataAdapter:- DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code.

// This method is used to bind gridview from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
con.Close();
}

 What is Method overloading and overriding?
Method Overloading:-Creating a multiple methods in a class with same name but different parameters and types is called as method overloading. Method overloading is the example of Compile time polymorphism which is done at compile time.
Method overloading can be achieved by using following things:
·         By changing the number of parameters used.
·         By changing the order of parameters.
·         By using different data types for the parameters.

Method overriding:- Creating the method in a derived class with same name, same parameters and same return type as in base class is called as method overriding.
Method overriding is the example of run time polymorphism, how it is the part of run time polymorphism i will explain in detail.
Some Key Points of Method overriding
Method overriding is only possible in derived class not within the same class where the method is declared.
Only those methods are overrides in the derived class which is declared in the base class with the help of virtual keyword or abstract keyword.
 e.g
public class Account
  {  
    public virtual int balance()
    {  
        return 10;  
    }  
  }  
public class Amount:Account
{  
    public override int balance()  
    {  
        return 500; 
    }  
}


 Output of the above Program is
·         10 and 500

What are the Design patterns?
There are 3 types of Patterns
                                                                                                       I.            Creational Patterns
                                                                                                    II.            Structural Patterns
                                                                                                 III.            Behavioral Patterns
Creational Patterns
Abstract Factory: -    Creates an instance of several families of classes.
Builder: -        Separates object construction from its representation.
Factory Method: -     Creates an instance of several derived classes.
Prototype: -    A fully initialized instance to be copied or cloned.
Singleton: -     A class of which only a single instance can exist.
Structural Patterns
Adapter: -      Match interfaces of different classes.
Bridge: -         Separates an object’s interface from its implementation.
Composite: -   A tree structure of simple and composite objects.
Decorator: -   Add responsibilities to objects dynamically.
Façade: -        A single class that represents an entire subsystem.
Flyweight: -    A fine-grained instance used for efficient sharing.
Proxy: - An object is representing another object.

Behavioral Patterns
Chain of Resp: - A way of passing a request between a chain of objects.
Command: -   Encapsulate a command request as an object.
Interpreter: -  A way to include language elements in a program.
Iterator: -       Sequentially access the elements of a collection.
Mediator: -     Defines simplified communication between classes.
Memento: -     Capture and restore an object's internal state.
Observer: -     A way of notifying change to a number of classes.
State: -            Alter an object's behavior when its state changes.
Strategy: -      Encapsulates an algorithm inside a class.
Template Method: -  Defer the exact steps of an algorithm to a subclass.
Visitor: -         Defines a new operation to a class without change.

What is Postback?
postback is initiated by the browser, and reloads the whole page, usually when a control on the page (e.g. a button) is changed. With some controls (e.g. Checkboxes), you choose if changing the control should result in a postback. This property is called AutoPostback.

A postback is initiated by the browser, and reloads the whole page, usually when a control on the page (e.g. a button) is changed.
With some controls (e.g. Checkboxes), you choose if changing the control should result in a postback. This property is called AutoPostback.

What is the difference between Master page and Page Layout?
Master page is a control residing into the main form.
Layouts are a different programming beast - they render all other content.