Anda di halaman 1dari 208

WHAT IS CLASS?

-> A class is a constructs that enables you to create your own custom types by
grouping together variables of other types, methods and events.

Some Key points about classes:


-----------------------------
->Classes are reference types that hold the object created dynamically in a heap.
->All classes have a base type of System.Object.
->The default access modifier of a class is Internal.
->The default access modifier of methods and variables is Private.
->Directly inside the namespaces declarations of private classes are not allowed.

The following are types of classes in C#:


-----------------------------------------
1.Abstract Class
2.Partial Class
3.Sealed Class
4.Static Class
===================================================================================
==================================
kWHAT IS OBJECT?
->Object is representative of the class and is responsible for memory allocation of
its data members and functions.
->For example, A �Bike� usually has common elements such as bike color, engine,
mileage etc. In OOP terminology these would be called as a Class Properties or
Attributes of a Bike object.
===================================================================================
==================================
WHAT IS METHOD?
-> A method is a code block that contains a series of statements. A program causes
the statements to be executed by calling the method and specifying any required
method arguments.
->For example, if you consider �Bike� as a class then its behavior is to get bike
color, engine, mileage etc.
===================================================================================
==================================
WHAT IS ABSTRACTION?
-> Abstraction is nothing but showing only what is necessasary.
->Abstraction means showing only what is necessasary, without showing its inner
details or hiding internal implementation
->We can enhance the internal implementation without effecting outside world.
Abstraction provides security. A class contains lot of data and the user does not
need the entire data.
->The advantage of abstraction is that every user will get his own view of the data
according to his requirements and will not get confused with unnecessary data.
Realworld Example:
-----------------
->A Postman - He is not bothered what is inside your parcel. He's job is to read
the address and deliver. It's abstraction.
===================================================================================
==================================
WHAT IS ENCAPSULATION?
->Encapsulation is nothing but hiding complexity.
->Encapsulation is the technique of making the fields in a class private and
providing access to the fields via public methods.
->If a field is declared private, it cannot be accessed by anyone outside the
class, thereby hiding the fields within the class. For this reason, encapsulation
is also referred to as data hiding (not data security).
->Thus encapsulation is said to be providing �access control� through which we can
control which parts of the program can access the members of any class and thus
prevent misuse. Various access controls are public, private and protected.
->Encapsulation can be described as a protective barrier that prevents the code and
data being randomly accessed by other code defined outside the class.
->The main benefit of encapsulation is the ability to modify our implemented code
without breaking the code of others who use our code. With this feature
Encapsulation gives maintainability, flexibility and extensibility to our
code.
Realworld Example:
------------------
->A Washing Machine and It's Power Button
What is the function that power button does? Switches the machine on (obviously).
But did u ever imagined the inside mechanism. Doesn't matter unless it's
functioning well. That's encapsulation. The object is wrapped and inner
details are hidden. Only thing is that object can be called and used. User
friendly!
===================================================================================
==================================
GIVE EXAMPLE FOR ABSTRACTION AND ENCAPSULATION?
->That means hidden part of class acts like Encapsulation and exposed part of class
acts like Abstraction.

public class Customer


{
public string customerNo;
public string customerName;

public void Add()


{
Validate();
CreateDBObjects(); // hiding complexity is encapsulation
// code for adding customer data to database
}

private bool Validate()


{
// code for validating customer data
return true;
}

private void CreateDBObjects()


{
// code for db objects creation
}
}

class Program
{
static void Main(string[] args)
{
Customer objCustomer = new Customer();
objCustomer.customerNo = "10001";
objCustomer.customerName = "Rakesh";

objCustomer.Add(); //showing only what is necessasary is abstraction


}
}
===================================================================================
==================================
WHAT IS INHERITANCE?
=> Inheritance allows you to define a child class that reuses (inherits), extends,
or modifies the behavior of a parent class.
=> The class whose members are inherited is called the base class. The class that
inherits the members of the base class is called the derived class. A derived class
can have only one direct base class.
=> Inheritance provides reusability by allowing us to extend an existing class.

Real world Example:


-------------------
->Let�s take a Bike example again. A Bike manufacturer uses same mechanism of
existing equipment version of the bike while launching a new version with some
additional added functionality. This allows manufacturer to save their time and
efforts both.
->The main advantage of extending classes is that it provides a convenient way to
reuse existing fully tested code in different context thereby saving lots of time
with existing coding and its model style.
->Thus, here conclusion is that �Base/Parent� classes are automatically
instantiated before �Child/Derived� classes.
===================================================================================
==================================
WHAT IS POLYMORPHISM?
-> Polymorphism is a Greek word that means "many-shaped".
-> Polymorphism means One function behaves in different ways/forms.

Real world Example:


-------------------
->Your mobile phone, one name but many functionalities:
As phone
As camera
As mp3 player
As radio
(OR)
->A man role changes at home, college, and outside the home.

->With polymorphism, the same method or property can perform different actions
depending on the run-time type of the instance that invokes it.
->There are two types of polymorphism:
Static or compile time polymorphism
Dynamic or runtime polymorphism

Compile time polymorphism:


--------------------------
=> Compile time polymorphism is implemented through method overloading.
=> Compile time polymorphism is executed at the compile-time since the compiler
knows which method to execute depending on the number of parameters and their data
types.
=> When we compile the class, the compiler binds the appropriate method to the
object based on the method's arguments. This is called early binding and this
process is referred to as compile time polymorphism.
=> Compile time polymorphism is refered as static polymorphism.

Method Overloading:-
--------------------
->The Method Overloading means more than one method having same name but different
signatures (or parameters) in the same or different class.
->Advantage: Execution will be fast because everything about the method is known to
compiler during compilation.
->Disadvantage: It has lack of flexibility.
Example � [Method Overloading]:
-------------------------------
public class Base
{
//1st: same method name, return type (object) but different parameter type
(object)
public object Display(object a)
{
return (a);
}
//2nd: same method name, return type (int) but different parameter type
(int)
public int Display(int a)
{
return (a);
}
}
public class Program
{
public static void Main(string[] args)
{
Base objBase = new Base();
int val = 7;
//here 2nd method will be called with type "int"
Console.WriteLine(objBase.Display(val));
Console.Read();
}
}
->In above example, when you run the program, Display(int a) method will be called
first because val is of type int at compile time. The assigned val is only refer
to as a int at execution time.
Example Result:7

Runtime polymorphism:
---------------------
=> Runtime time polymorphism is implemented through method overriding.
=> Runtime time polymorphism is executed at the run-time since the compiler does
not knows the method to be executed.=> Runtime time polymorphism is refered as
dynamic polymorphism.

Method Overriding:-
-------------------
->The Method Overriding means having two methods with same name and same signature,
one method in base class and other method in derived class. It must require
changing the behavior of the base class methods in derived class to use its
functionality differently.
->Advantage: It has flexibility to adjust object types at runtime.
->Disadvantage: Execution will be slow as compiler has to get the information about
the method to execute at runtime.
->We need to use either virtual methods or abstract method to allow the derived
class to override a method of the base class.

Example � [Method Overriding by using virtual method]:


------------------------------------------------------
public class Base
{
public virtual string BlogName()
{
return "AspnetO";
}
}
public class Child : Base
{
//same method name with same signature/parameters
public override string BlogName()
{
return "AspnetO � Quick Way To Learn Asp.net";
}
}

public class Program


{
public static void Main(string[] args)
{
Base objBase = new Child();
Console.WriteLine(objBase.BlogName());
Console.Read();
}
}
->In above example, when you run the program, at compile time the type of objBase
is Base but it will still call the child class�s override method because at the
runtime, the type of the objBase object refers to is Child.
Example Result:
AspnetO � Quick Way To Learn Asp.net
===================================================================================
==================================
WHAT IS CONSTRUCTOR?
-> It's a special method present under a class responsible for initializing the
variables of that class.
-> The name of the constructor method is exactly the same name of the class in
which it was present and more over it's a non-value returning method.
-> Each and every class requires this constructor if we want to create the instance
of that class.
-> If we create any class without constructor, the compiler will automatically
create one default constructor for that class.There is always at least one
constructor in every class.
-> A class can have any number of constructors and constructors don�t have any
return type, not even void and within a class we can create only one static
constructor.Generally constructor name should be same as class name.

Key points to note about constructor are:


-----------------------------------------
->If no constructor defined then the CLR(Common Language Runtime) will provide an
implicit constructor which is known as a Default Constructor.
->Constructor doesn�t return a value.
->Constructors can be overloaded.
->A class can have any number of constructors and they vary with the number of
arguments that are passed, which is they should have different parameters or
signatures.
->We don�t use references or pointers on constructors because their addresses
cannot be taken.
->Constructor doesn�t be declared with the virtual keyword.

Types of Constructors
---------------------
Basically constructors are 5 types those are
1.Default Constructor
2.Instance Constructor
3.Copy Constructor
4.Static Constructor
5.Private Constructor

Default Constructor
-------------------
If you don't provide a constructor for your class, C# creates one by default that
instantiates the object and sets member variables to the default values.

class Sample
{
public string param1, param2;
public Sample() // Default Constructor
{
param1 = "Welcome";
param2 = "Aspdotnet-Suresh";
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample(); // Once object of class created automatically
constructor will be called
Console.WriteLine(obj.param1);
Console.WriteLine(obj.param2);
Console.ReadLine();
}
}

Instance Constructors:
----------------------
A constructor with at least one parameter is called as Instance constructor. In
Instance constructor we caninitialize each instance of the class to different
values like as shown below

class Sample
{
public string param1, param2;
public Sample(string x, string y) // Declaring Parameterized constructor with
Parameters
{
param1 = x;
param2 = y;
}
}
class Program
{
static void Main(string[] args)
{
Sample obj=new Sample("Welcome","Aspdotnet-Suresh"); // Parameterized Constructor
Called
Console.WriteLine(obj.param1 +" to "+ obj.param2);
Console.ReadLine();
}
}

Constructor Overloading
-----------------------
In c# we can overload constructor by creating another constructor with same method
name and different parameters like as shown below

class Sample
{
public string param1, param2;

public Sample() // Default Constructor


{
param1 = "Hi";
param2 = "I am Default Constructor";
}
public Sample(string x, string y) // Declaring Parameterized constructor with
Parameters
{
param1 = x;
param2 = y;
}

class Program
{
static void Main(string[] args)
{
Sample obj = new Sample(); // Default Constructor will Called
Sample obj1=new Sample("Welcome","Aspdotnet-Suresh"); // Parameterized
Constructor will Called
Console.WriteLine(obj.param1 + ", "+obj.param2);
Console.WriteLine(obj1.param1 +" to " + obj1.param2);
Console.ReadLine();
}
}

Copy Constructor
----------------
->C# doesn't provide a copy constructor for objects, but you can write one
yourself.
->A parameterized constructor that contains a parameter of same class type is
called as copy constructor.
->The main purpose of copy constructor is to initialize new instance to the values
of an existing instance.

class Person
{
// Copy constructor.
public Person(Person previousPerson)
{
Name = previousPerson.Name;
Age = previousPerson.Age;
}

// Instance constructor.
public Person(string name, int age)
{
Name = name;
Age = age;
}

public int Age { get; set; }


public string Name { get; set; }

public string Details()


{
return Name + " is " + Age.ToString();
}
}

class TestPerson
{
static void Main()
{
// Create a Person object by using the instance constructor.
Person person1 = new Person("George", 40);

// Create another Person object, copying person1.


Person person2 = new Person(person1);

// Change each person's age.


person1.Age = 39;
person2.Age = 41;

// Change person2's name.


person2.Name = "Charles";

// Show details to verify that the name and age fields are distinct.
Console.WriteLine(person1.Details());
Console.WriteLine(person2.Details());

// Keep the console window open in debug mode.


Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
// Output:
// George is 39
// Charles is 41

Static Constructor
------------------
->A static constructor is used to initialize any static data, or to perform a
particular action that needs to be performed once only.
->It is called automatically before the first instance is created or any static
members are referenced.

class SimpleClass
{
// Static variable that must be initialized at run time.
static readonly long baseline;

// Static constructor is called at most one time, before any


// instance constructor is invoked or member is accessed.
static SimpleClass()
{
baseline = DateTime.Now.Ticks;
}
}
Importance points of static constructor
---------------------------------------
->A static constructor does not take access modifiers or have parameters.
->A static constructor is called automatically to initialize the class before the
first instance is created or any static members are referenced.
->A static constructor cannot be called directly.
->The user has no control on when the static constructor is executed in the
program.
->A typical use of static constructors is when the class is using a log file and
the constructor is used to write entries to this file.
->Static constructors are also useful when creating wrapper classes for unmanaged
code, when the constructor can call the LoadLibrary method.
->If a static constructor throws an exception, the runtime will not invoke it a
second time, and the type will remain uninitialized for the lifetime of the
application domain in which your program is running.
->Static constructor will not accept any parameters because it is automatically
called by CLR.
->Static constructor will not have any access modifiers.
->Only one static constructor will allowed.

Private Constructor
-------------------
->A private constructor is a special instance constructor. It is generally used in
classes that contain static members only.
->If a class has one or more private constructors and no public constructors, other
classes (except nested classes) cannot create instances of this class. This mean we
can neither create the object of the class nor it can be inherit by other class.
->The main purpose of creating private constructor is used to restrict the class
from being instantiated when it contains every member as static.

public class Counter


{
private Counter() { }
public static int currentCount;
public static int IncrementCount()
{
return ++currentCount;
}
}

class TestCounter
{
static void Main()
{
Counter.currentCount = 100;
Counter.IncrementCount();
Console.WriteLine("New count: {0}", Counter.currentCount);

// Keep the console window open in debug mode.


Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
// Output: New count: 101

Important points of private constructor


---------------------------------------
->One use of private construct is when we have only static member.
->Once we provide a constructor that is either private or public or any, the
compiler will not allow us to add public constructor without parameters to the
class.
->If we want to create object of class even if we have private constructors then we
need to have public constructor along with private constructor
===================================================================================
==================================
WHAT IS DESTRUCTOR?
->Destructors are used to destruct instances of classes.
->The programmer has no control on when the destructor is going to be executed
because this is determined by the Garbage Collector.
->The garbage collector checks for objects that are no longer being used by the
application. It considers these objects eligible for destruction and reclaims their
memory.
->Destructors are also called when the program exits.
->When a destructor executes what is happening behind the scenes is that the
destructor implicitly calls the
Object.Finalize() method on the object's base class.
->A destructor is a function with the same name as the name of the class but
starting with the character ~.

Example:
--------
class A
{
public A()
{
Console.WriteLine("Creating A");
}
~A()
{
Console.WriteLine("Destroying A");
}
}

class B:A
{
public B()
{
Console.WriteLine("Creating B");
}
~B()
{
Console.WriteLine("Destroying B");
}

}
class C:B
{
public C()
{
Console.WriteLine("Creating C");
}

~C()
{
Console.WriteLine("Destroying C");
}
}
class App
{
public static void Main()
{
C c=new C();
Console.WriteLine("Object Created ");
Console.WriteLine("Press enter to Destroy it");
Console.ReadLine();
c=null;
//GC.Collect();
Console.Read();
}

Output:
-------
Creating A
Creating B
Creating C
Object Created
Press enter to Destroy it
Destroying C
Destroying B
Destroying A

Remember that a destructor can't have any modifiers like private, public etc. If we
declare a destructor with a modifier, the compiler will show an error.Also
destructor will come in only one form, without any arguments. There is no
parameterized destructor in C#. Destructors are invoked automatically and can't be
invoked explicitly.

Key points to note about destructor are:


----------------------------------------
->Destructors cannot be defined in structs. They are only used with classes.
->A class can only have one destructor.
->Destructors cannot be inherited or overloaded.
->Destructors cannot be called. They are invoked automatically.
->A destructor does not take modifiers or have parameters.

Calling the garbage collector


-----------------------------
You can force the garbage collector to do clean up by calling the GC.Collect
method, but in most cases, this should be avoided because it may result in
performance issues.
===================================================================================
==================================
WHAT IS ABSTRACT CLASS AND WHEN TO USE IT?
->Classes can be declared as abstract by putting the keyword abstract before the
class definition.
public abstract class A
{
// Class members here.
}
->An abstract class cannot be instantiated. The purpose of an abstract class is to
provide a common definition of a base class that multiple derived classes can
share.
->Abstract class can have both abstract as well as non-abstract methods.
->Abstract class are frequently either partially implemented, or not at all
implemented.
Why can't we create objects for abstract class?
-----------------------------------------------
Abstract class means it may contain methods which do not have definition as well as
methods with definition.
So if we allow to create an object and the object calls a method which has no
definition, then what must CLR do?
So object creation of the abstract class is not allowed directly. The sub class
when extends the abstract class, it must provide definition to the abstract
methods. Hence now you can allow object creation safely.

Why do we need an Abstract Class?


---------------------------------
With an Abstract Class, we can provide some kind of common functionality for all
derived classes to extend from. This is useful to avoid code duplication in many
cases.

Suppose we are defining an iPhone class for Apple and then inheriting it to iPhone5
and iPhone5s subclasses. Practically we don't want an object of an iPhone class
since we first need to know the model of iPhone. So, the iPhone class should be an
abstract class that contains some predefined functions like Call() and SMS() for
all iPhone models to share . We can also add abstract methods like Model() and
Color() into the iPhone class that must be implemented by all the subclasses
inheriting iPhone. The main advantage of this approach is, whenever we inherit the
iPhone class into a derived class, say iPhone5s, we need not define the Call() and
SMS() methods again. We just need to implement the abstract methods and we are good
to go. It helps to provide default functionality in all the derived classes and
also avoids code duplication.

Abstract classes are also useful in the case of modifications to the project. If
you plan on updating the base class in your project, it is better to make the class
abstract. Because you can define a functionality in an abstract base class and
automatically all the inheriting classes will have the same functionality without
disturbing the hierarchy.

Key Points:
-----------
->We cannot create an object of Abstract Class but we can create a reference of it.
public static void Main(string[] args)
{
//We can't do this
//absClass cls = new absClass();
//We can do this
absClass cls;
}
->An inheritance between abstract to abstract classes is possible. We don't need to
implement abstract methods of the base abstract class into a derived abstract
class. We can implement it later in concrete classes.
abstract class absClassB: absClassA //Abstract to Abstract Inheritance
{
}
->An abstract class can never be sealed or static.
->An abstract class can have abstract as well as non abstract methods.
->The abstract keyword can be used with class, methods, properties, indexers and
events.
->Abstract members can only be declared inside an abstract class.
->An abstract member cannot be static or private.
->An abstract method cannot be marked virtual.
->A concrete class cannot inherit more than one abstract class, in other words
multiple Inheritance is not possible.
->Without an abstract class, we cannot implement the Template Method Pattern.

using System;
namespace AbstractClassDemo
{
abstract class iPhone
{
//Non-Abstract Method
public void Call()
{
Console.WriteLine("Call Method: This method provides Calling
features");
}
//Abstract Method
public abstract void Model();
}

class iPhone5s: iPhone


{
//Abstract Method Implementation
public override void Model()
{
Console.WriteLine("Model: The model of this iPhone is iPhone5s");
}

//Derived Class Local Method


public void LaunchDate()
{
Console.WriteLine("Launch Date: This iPhone was launched on 20-
September-2013");
}
}

class Program
{
static void Main(string[] args)
{
iPhone5s iphone5s = new iPhone5s();
iphone5s.Call();
iphone5s.Model();
iphone5s.LaunchDate();
Console.ReadKey();
}
}
}
===================================================================================
==================================
WHAT IS INTERFACE AND WHEN TO USE IT?
-> Interface is like a pure abstract class means it has no implementation and which
cannot be instantiated.
-> An interface acts as a contract between itself and any class or struct which
implements it. It means a class or struct that implement an interface is bound to
implement all its members.
-> Interface has only member�s declaration or signature and implicitly every member
of an interface is public and abstract.
->An interface cannot contain fields,constant, members, constructors, destructors
and static members.
However, there is the advantage of using an interface over an abstract class, that
is "Multiple Inheritance Support".

Why do we need an interface?


----------------------------
Suppose we need to define a class for a Smart Phone. The class can have functions
like OS, AppStore and Call and SMS. The Smartphone can be either Android based or
iOS based and cannot be both. There is no common functionality between an Android
and iOS Smartphone, so we don't need to provide any default functionality. One
approach is to make the SmartPhone class abstract and also all its members
abstract. This approach works fine and several concrete classes like Samsung,
Apple, HTC can inherit from it.

Now, after a few days Apple wants to add a Touch ID feature to its Smartphone. You
can add TouchID as an abstract method in your abstract base class SmartPhone. But
what if HTC doesn't want that feature and neither does Samsung? So, the TouchID
method cannot be placed inside the abstract class SmartPhone. An alternative is to
define another abstract class Features and add the TouchID method to it. This is
also a bad idea since C# doesn't support inheritance of multiple classes (abstract
or concrete) into a derived class.

In this situation, an interface is useful and plays a vital role in solving the
problem. An interface provides only the method definitions, just like an abstract
class, but can be useful in multiple inheritances. You can make the Features class
an interface and add the TouchID method to it. It provides only the method
signature and whichever class inherits it can implement it in its own way. It is
also completely valid for a class to inherit more than one interface in C#. Also,
we can make the SmartPhone class an interface instead of an abstract class. It is
better instead of making a pure abstract class, we can use interfaces.

using System;
namespace InterfaceDemo
{
interface ISmartPhone
{
void OS();
void AppStore();
}

//New Interface meant only for Apple Class


interface IFeatures
{
void TouchID();
}

class Apple: ISmartPhone, IFeatures


{
//OS Method Implementation
public void OS()
{
Console.WriteLine("OS Method: The OS of this smartphone is iOS8");
}

//AppStore Method Implementation


public void AppStore()
{
Console.WriteLine("AppStore Method: The Application Store of this
smartphone is iTunes");
}
//TouchID Method Implementation
public void TouchID()
{
Console.WriteLine("TouchID Method: This method provides Touch/Gesture
Control features.");
}
}

class Samsung : ISmartPhone


{
//OS Method Implementation
public void OS()
{
Console.WriteLine("OS Method: The OS of this smartphone is Android");

//AppStore Method Implementation


public void AppStore()
{
Console.WriteLine("AppStore Method: The Application Store of this
smartphone is Google Play");
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("//////////////////// - Interface Demo
- //////////////////// \n");
Console.WriteLine("Apple SmartPhone:");
Apple apple = new Apple();
apple.OS();
apple.AppStore();
apple.TouchID();

Console.WriteLine("\n\n");
Console.WriteLine("Samsung SmartPhone:");
Samsung samsung = new Samsung();
samsung.OS();
samsung.AppStore();
Console.ReadKey(); }
}
}

Key Points
----------
->Interface Reference Variable
An interface has no implementation and cannot be instantiated. However, it can be
referenced to the class object that implements it. It may be noted that the object
can only access the inherited members of the interface. Consider the following
code:

using System;
namespace InterfaceDemo
{
interface IDriveable
{
void Drive();
}

class Car : IDriveable


{
public void Drive()
{
Console.WriteLine("Car Class: I can drive a Car.");
}
}

class Truck : IDriveable


{
public void Drive()
{
Console.WriteLine("Truck Class: I can drive a Truck.");
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("//////////////////// - Interface Demo
- //////////////////// \n");
IDriveable DriveCar = new Car();
IDriveable DriveTruck = new Truck();

DriveCar.Drive(); //Calls Car's Drive() method


DriveTruck.Drive(); //Calls Truck's Drive() method
Console.ReadKey();
}
}
}
->If you have some kind of default functionality to share across classes in the
hierarchy, you can use an abstract class. But if you don't have any default
implementation and just need to define contracts for derived classes to follow;
interface is the most preferred choice.
->It is a standard rule when using an interface, be sure you have done it right the
first time. Once the interface is implemented by derived classes, it is difficult
to update or modify the interface since everyone else's code breaks.
->Explicit Interface Implementation
When working with interfaces, there occurs a situation when a class implements two
interfaces and both the interfaces contain a member with the same signature. When
the class provides a definition to interface members, it gets confused about which
member gets the definition since both have the same name. In that case, we'll an
Explicit Interface Implementation.
Suppose we have two interfaces ICreditCard and IDebitCard and both of these
interfaces have the same method signature called CardNumber and a class Customer
implements both of these interfaces.

using System;
namespace InterfaceDemo
{
//First Interface IDebitCard
interface IDebitCard
{
void CardNumber();
}

//Second Interface ICreditCard


interface ICreditCard
{
void CardNumber();
}

//Customer Class implements both the interfaces


class Customer: IDebitCard, ICreditCard
{
void IDebitCard.CardNumber()
{
Console.WriteLine("Debit Card Number: My Card Number is 12345XXXXX");
}
void ICreditCard.CardNumber()
{
Console.WriteLine("Credit Card Number: My Card Number is 98999XXXXX");

}
public void CardNumber()
{
Console.WriteLine("Customer ID Number: My ID Number is 54545XXXXX");
}
}

class Program
{
static void Main(string[] args)
{
Console.WriteLine("////////////////////- Implicit and Expliction
Implementation -//////////// \n\n");
Customer customer = new Customer();
IDebitCard DebitCard = new Customer();
ICreditCard CreditCard = new Customer();

customer.CardNumber();
DebitCard.CardNumber();
CreditCard.CardNumber();
Console.ReadKey();
}
}
}
===================================================================================
==================================
WHEN TO USE ABSTRACT CLASS AND INTERFACE IN REALTIME?
->If you are planing to creating multiple versions of your component, create an
abstract class. Abstract classes provide a simple and easy way to version your
components. By updating the base class, all inheriting classes are
automatically updated with the change. On the other hand, Interfaces cannot be
changed once created.If a new version of an interface is required, you must create
a whole new interface.
->If you have some kind of default functionality to share across classes in the
hierarchy, you can use an abstract class. But if you don't have any default
implementation and just need to define contracts for derived classes to follow;
interface is the most preferred choice.
->If you are designing small, concise bits of functionality, use interfaces. If you
are designing large functional units, use an abstract class.
->If you want to provide common, implemented functionality among all
implementations of your component, use an abstract class. Abstract classes
allow you to partially implement your class, whereas interfaces contain no
implementation for any members.
===================================================================================
==================================
DIFFERENCE BETWEEN AN ABSTRACT CLASS AND AN INTERFACE?
->An interface can inherit from another interface only and cannot inherit from an
abstract class, where as abstract class can inherit from another abstract class
or interface.
->An Abstract class doesn't provide full abstraction but an interface does provide
full abstraction; i.e. both a declaration and a definition is given in an
abstract class but not so in an interface.
->Using Abstract we can not achieve multiple inheritance but using an Interface we
can achieve multiple inheritance.
->We can not declare a member field in an Interface but we can declare in abstract
class.
->We can not use any access modifier i.e. public , private , protected , internal
etc. because within an interface by default everything is public but we can use
it in abstract class.
->An Interface member cannot be defined using the keyword static, virtual, abstract
or sealed.
===================================================================================
==================================
WHAT IS BOXING AND UNBOXING? WHAT ARE THE ADVANTAGES AND DISADVANTAGES OF IT?
Boxing and Unboxing both are used for type conversion.
Boxing:
-------
Implicit conversion of a value type to a reference type(object), is known as
Boxing. When the CLR boxes a value means, it wraps the value inside a System.Object
and stores it on the managed heap.

Example:-
int i = 123;

// Boxing copies the value of i into object o.


object o = i; // implicit boxing
object o = (object)i; // explicit boxing

Unboxing:
---------
-> Explicit conversion of same reference type (which is being created by boxing
process), back to a value type is known as unboxing.
-> In unboxing process, boxed value type is unboxed from the heap and assigned to a
value type which is being allocated on the stack.

Example:-
int i = 123; // a value type
object o = i; // boxing
int j = (int)o; // unboxing

Boxing may be done implicitly, but unboxing have to be explicit by code.


->The Advantage of boxing and unboxing is that we can convert one type of the
object to another type.
->The disadvantage is that it requires lot of memory and CPU cycles to convert from
one type to another type.

KeyPoints:-
-----------
-> Sometimes boxing is necessary, but you should avoided it if possible, since it
will slow down the performance and increase memory requirements.
-> For example, when a value type is boxed, a new reference type is created and the
value is copied from the value type to the newly created reference type. This
process takes time and required extra memory (around twice the memory of the
original value type).

->Attempting to unbox a null causes a NullReferenceException.


int? stackVar = null;
// Boxing= Integer is created on the Heap
object boxedVar = stackVar;
// NullReferenceException
int unBoxed = (int)boxedVar; //Object reference not set to an instance of an
object.
->Attempting to unbox a reference to an incompatible value type causes an
InvalidCastException.
int stackVar = 12;
// Boxing= Integer is created on the Heap
object boxedVar = stackVar;
// InvalidCastException
float unBoxed = (float)boxedVar; //Specified cast is not valid.

Performance:-
--------------
In relation to simple assignments, boxing and unboxing are computationally
expensive processes. When a value type is boxed, a new object must be allocated and
constructed. To a lesser degree, the cast required for unboxing is also expensive
computationally.
===================================================================================
==================================
WHAT IS ASSEMBLY,GAC? WHERE THEY ARE PHYSICALLY LOCATED?
->Assembly is the smallest unit of deployment of a .net application. It can be a
dll or an exe.
->The assembly typically contains .NET code in MSIL (Microsoft Intermediate
language) that will be compiled to native code ("JITted" - compiled by the Just-In-
Time compiler) the first time it is executed on a given machine. That compiled code
will also be stored in the assembly and reused on subsequent calls.
->The assembly can also contain resources like icons, bitmaps, string tables and so
on. Furthermore, the assembly also contains metadata in the assembly manifest -
information like version number, strong name, culture, referenced assemblies and so
forth.

There are 3 types of assemblies-


1.Private Assembly
The dll or exe which is sole property of one application only. It is generally
stored in application root folder.

2.Shared Assembly
It is a dll which can be used by multiple applications at a time. A shared
assembly is stored in GAC i.e Global Assembly Cache.
<drive>:\windows\assembly <-- GAC folder
We can find all base class libraries under GAC.
We can only get a strong named assembly into the GAC.
GAC contains multiple assemblies and it is identified by PUBLIC KEY TOKEN.

3.Satellite Assembly
->A .NET Framework assembly containing resources specific to a given language.
Using satellite assemblies, you can place the resources for different languages
in different assemblies, and the correct assembly is loaded into memor only if
the user elects to view the application in that language."
->This means that you develop your application in a default language and add
flexibility to react with change in the locale. Say, for example, you developed
your application in an en-US locale. Now, your application has multilingual
support. When you deploy your code in, say, India, you want to show labels,
messages shown in the national language which is other than English.
->Satellite assemblies give this flexibility. You create any simple text file with
translated strings, create resources, and put them into the bin\debug folder.
That's it. The next time, your code will read the CurrentCulture property of the
current thread and accordingly load the appropriate resource.

GAC (Global Assembly Cache)-


---------------------------
When the assembly is required by more than one project or application, we need to
make the assembly with strong name and keep it in GAC or in Assembly folder by
installing the assembly with the GACUtil command.
Path :- C:\WINDOWS\assembly

To make the assembly with strong name:


--------------------------------------
SN -k MyDll.dll
And to install it in GAC:
GacUtil -i MyDll.dll
GAC assemblies are physically stored in Assembly folder in the system.
===================================================================================
==================================
WHAT ARE VALUE TYPES AND REFERENCE TYPES?
Value types are stored in the Stack whereas Reference types stored on Heap.
Value types:
------------
int, enum , byte, decimal, double, float, long, struct

Reference Types:
----------------
string , class, interface, object, delegate
===================================================================================
==================================
DIFFERENCE BETWEEN CONSTANT AND READONLY?
Constant:
---------
Constant fields must be initialized at the time of declaration only and after that
they cannot be modified.
By default constant are static, so you cannot define a constant type as static.

Realtime Example:-
------------------
public const double Pi = 3.14;

A const field is a compile-time constant. A constant field can be initialized with


a constant expression which must be fully evaluated at compile time.

void Calculate(int Z)
{
const int X = 10, X1 = 50;
const int Y = X + X1; //no error, since its evaluated a compile time
const int Y1 = X + Z; //gives error, since its evaluated at run time
}
You can apply const keyword to built-in value types (byte, short, int, long, char,
float, double, decimal, bool), enum, a string literal, or a reference type which
can be assigned with a value null.
const MyClass obj1 = null;//no error, since its evaluated a compile time
const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time

Constants can be marked as public, private, protected, internal, or protected


internal access modifiers.
Use the const modifier when you sure that the value of a field or local variable
would not be changed.

ReadOnly:
---------
A readonly field can be initialized either at the time of declaration or with in
the constructor of same class. Therefore, readonly fields can be used for run-time
constants.

class MyClass
{
readonly int X = 10; // initialized at the time of declaration
readonly int X1;

public MyClass(int x1)


{
X1 = x1; // initialized at run time
}
}

Real time Example:-


-------------------
private static readonly string ConnectionString = ConnString.GetConnectionString();

Explicitly, you can specify a readonly field as static since, like constant by
default it is not static. Readonly keyword can be apply to value type and reference
type (which initialized by using the new keyword) both. Also, delegate and event
could not be readonly.
Use the readonly modifier when you want to make a field constant at run time.
===================================================================================
==================================
DIFFERENCE BETWEEN REF AND OUT PARAMETERS?
-ref tells the compiler that the object is initialized before entering the
function, while out tells the compiler that the object will be initialized inside
the function.
-When we use REF, data can be passed bi-directionally.When we use OUT data is
passed only in a unidirectional way (from the called method to the caller method).
-Both ref and out are treated differently at run time and they are treated the same
at compile time.

Ref:
----
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:
----
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.
Program with ref and out keyword
--------------------------------
public class Example
{
static void Example1(ref int value) //called method
{
value = 1; // optional
}
static void Example2(out int value) //called method
{
value = 2; //must be initialized
}

public static void Main() //calling method


{
int val1 = 0; //must be initialized ref
int val2; //optional out

Example1(ref val1); // calling method


Console.WriteLine(val1); // val1=1

Example2(out val2); // calling method


Console.WriteLine(val2); // val2=2
}
}

/* Output
1
2
*/

When to use ref and out parameters:


-----------------------------------
If you want return multiple values from function then ref and out parameters are
really usefull.

Example with REF:-


static void Main(string[] args)
{
int a = 10;
int b = 20;
int add = 0;
int multiply = 0;
Add_Multiply(a, b, ref add, ref multiply);
Console.WriteLine(add);
Console.WriteLine(multiply);
}
private static void Add_Multiply(int a, int b, ref int add, ref int multiply)
{
add = a + b;
multiply = a * b;
}

Example with OUT:-


static void Main(string[] args)
{
int a = 10;
int b = 20;
int add;
int multiply;
Add_Multiply(a, b, out add, out multiply);
Console.WriteLine(add);
Console.WriteLine(multiply);
}
private static void Add_Multiply(int a, int b, out int add, out int multiply)
{
add = a + b;
multiply = a * b;
}

Note:-
------
-Do not be confused with the concept of passing by reference and the concept of
reference type. These two concepts are not the same.
-A value type or a reference type can be passed to method parameter by using ref
keyword. There is no boxing of a value type when it is passed by reference.
-Properties cannot be passed to ref or out parameters since internally they are
functions and not members/variables.

Ref and out in method overloading:


----------------------------------
Both ref and out cannot be used in method overloading simultaneously. However, ref
and out are treated differently at run-time but they are treated same at compile
time (CLR doesn't differentiates between the two while it created IL for ref and
out). Hence methods cannot be overloaded when one method takes a ref parameter and
other method takes an out parameter. The following two methods are identical in
terms of compilation.

class MyClass
{
public void Method(out int a) // compiler error �cannot define overloaded�
{
// method that differ only on ref and out"
}
public void Method(ref int a)
{
// method that differ only on ref and out"
}
}

However, method overloading can be done, if one method takes a ref or out argument
and the other method takes simple argument. The following example is perfectly
valid to be overloaded.
class MyClass
{
public void Method(int a)
{

}
public void Method(out int a)
{
// method differ in signature.
}
}
===================================================================================
==================================
WHAT IS SEALED CLASS?
-> When sealed applied to a class, the sealed modifier prevents other classes from
inheriting from it. In the following example, class B inherits from class A, but no
class can inherit from class B.

class A {}
sealed class B : A {}

The following are some key points:


----------------------------------
-A Sealed class is created using the sealed keyword.
-To access the sealed members we must create an object of the class.
===================================================================================
==================================
WHAT IS COLLECTIONS AND GENERIC COLLECTIONS?
Non-generic Generic
------------- -----------------------
ArrayList -------------> List
HashTable -------------> Dictionary
SortedList -------------> SortedList
Stack -------------> Stack
Queue -------------> Queue

-> Collection classes are normally used to hold collection/group of values in


memory. A collection is a class, so you must create an instance of the class before
you can add elements to that collection.
-> Collections provide a more flexible way to work with groups of objects. Unlike
arrays, the group of objects you work with can grow and shrink dynamically as the
needs of the application change. For some collections, you can assign a key to any
object that you put into the collection so that you can quickly retrieve the object
by using the key.
-Each element can represent a value of a different type.
-Array Size is not fixed.
-Elements can be added / removed at runtime.

ArrayList
---------
-Arraylist is a class that is similar to an array, but it can be used to store
values of various types.
-An Arraylist doesn't have a specific size.
-Any number of elements can be stored.
kArrayList al = new ArrayList();
Note:
-Arraylist allocates memory for 4 items, whenever an object is created. When a
fifth item is added, memory for another 4 items are added.
-it reduces the memory allocated for the object.

HashTable:
----------
HashTable is similar to arraylist but represents the items as a combination of a
key and value.

SortedList:
-----------
-It is a class that has the combination of arraylist and hashtable.
-Represents the data as a key and value pair.
-Arranges all the items in sorted order.

GENERIC COLLECTIONS
-------------------
If your collection contains elements of only one data type, you can use one of the
classes inthe System.Collections.Generic namespace. A generic collection enforces
type safety so that no other data type can be added to it. When you retrieve an
element from a generic collection, you do not have to determine its data type or
convert it.
-Specific type
-Array Size is not fixed
-Elements can be added / removed at runtime.

Types of Generic Collections:


-----------------------------
List<int> lst = new List<int>();
Dictionary<int, string> dct = new Dictionary<int, string>();
SortedList<string, string> sl = new SortedList<string, string>();
Stack<string> stk = new Stack<string>();
Queue<string> q = new Queue<string>();
===================================================================================
==================================
WHAT ARE THE DIFFERENCES BETWEEN DICTONARY AND HASHTABLE?
Dictionary:
-----------
-It returns error if we try to find a key which does not exist.
-It is faster than a Hashtable because there is no boxing and unboxing.
-Only public static members are thread safe.
-Dictionary is a generic type which means we can use it with any specific data
type.

Hashtable:
----------
-It returns null if we try to find a key which does not exist.
-It is slower than dictionary because it requires boxing and unboxing.
-All the members in a Hashtable are thread safe,
-Hashtable is not a generic type
===================================================================================
==================================
DIFFERENCE BETWEEN OBJECT & VAR & DYNAMIC?
Object Var Dynamic:
------------------------
--Object was introduced with C# 1.0
Var was introduced with C# 3.0
Dynamic was introduced with C# 4.0

--It can store any kind of value, because object is the base class of all type
in .NET framework.
It can store any type of value, but It is mandatory to initialize var types at
the time of declaration.
It can store any type of the variable.

--Compiler has little information about the type.


It is type safe i.e. Compiler has all information about the stored value, so that
it doesn't cause any issue at run-time.
It is not type safe i.e. Compiler doesn't have any information about the stored
type.

--Object type can be passed as method argument and method also can return object
type.
Var type cannot be passed as method argument and method cannot return var type.
Var type work in the scope where it defined.
Dynamic type can be passed as method argument and method also can return dynamic
type.

--Need to cast object variable to original type to use it and performing desired
operations.
No need to cast because compiler has all information to perform operations.
Casting is not required but you need to know the properties and methods related
to stored type.

--Cause the problem at run time if the stored value is not getting converted to
underlying data type.
Doesn't cause problem because compiler has all information about stored value.
Cause problem if the wrong properties or methods are accessed because all the
information about stored value is get resolve only at run time.

--Useful when we don�t have more information about the data type.
Useful when we don�t know actual type i.e. type is anonymous.
Useful when we need to code using reflection or dynamic languages or with the COM
objects, because you need to write less code.
===================================================================================
==================================
WHAT ARE THE TYPES OF INHERITANCE?
Base class: is the class from which features are to be inherited into another
class.
Derived class: it is the class in which the base class features are inherited.

Single inheritance
------------------
It is the type of inheritance in which there is one base class and one derived
class.

Hierarchical inheritance
------------------------
This is the type of inheritance in which there are multiple classes derived from
one base class. This type of inheritance is used when there is a requirement of one
class feature that is needed in multiple classes.

Multilevel inheritance
----------------------
When one class is derived from another derived class then this type of inheritance
is called multilevel inheritance.

Multiple inheritance using Interfaces


-------------------------------------
C# does not support multiple inheritances of classes. To overcome this problem we
can use interfaces, we will see more about interfaces in my next article in detail.
===================================================================================
==================================
DIFFERENCE BETWEEN ARRAY AND ARRAYLIST?
Arrays:
-------
--These are strong type collection and allow to store fixed length
--Arrays belong to System.Array namespace
--In arrays we can store only one datatype either int, string, char etc�
--Boxing and Unboxing is not required.
--Elements cannot be inserted and deleted at runtime
string[] arr=new string[2];
arr[0] = "welcome";

ArrayLists:
-----------
--Array Lists are not strong type collection and size will increase or decrease
dynamically
--Arraylist belongs to System.Collection namespaces
--In arraylist we can store all the datatype values
--Boxig and Unboxing is required for every element because the datatype of arrylist
is object.
--Elements can be inserted and deleted at run time.
ArrayList strarr = new ArrayList();
strarr.Add("welcome"); // Add string values
===================================================================================
==================================
METHOD OVERLOADING AND OVERRIDING IN C#?
What is Method Overloading ?
-----------------------------
=> Creating multiple methods with same name but different signature(Type of
parameter, Number of parameters, Order of the parameters) in the class 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.

What is Method overriding?


--------------------------
=> The Method Overriding means having two methods with same name and same
signature, one method in base class and other method in derived class is called as
method overriding.
=> It must require changing the behavior of the base class methods in derived class
to use its functionality differently.
=> Method overriding is the example of run time polymorphism which is done at run
time.

Some Key Points of Method overriding:


--------------------------------------
=> Method overriding is only possible in base and derived classes 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.
===================================================================================
==================================
DIFFERENCE BETWEEN METHOD OVERLOADING AND METHOD OVERRIDING?
Overloading
-----------
=> Having same method name with different Signatures (parameters).
=> Overloading is the concept of compile time polymorphism.
=> Two functions having same name and return type, but with different type and/or
number of arguments is called as Overloading.
=> It doesn't need inheritance.
=> Method can have different data types.
=> Method can be different access modifiers.

Overriding
----------
=> Methods name and signatures must be same.
=> Overriding is the concept of run time polymorphism.
=> When a function of base class is re-defined in the derived class called as
Overriding.
=> It needs inheritance.
=> Method should have same data type.
=> Method should be public.
===================================================================================
==================================
WHAT IS DIFFERENCE BETWEEN A STRUCTURE AND A CLASS?
Class and struct both are the user defined data type but have some major
difference:
Struct:
-------
=> The struct is value type in C# and it inherits from System.Value Type.
=> Struct is usually used for smaller amounts of data.
=> Struct can�t be inherited to other type.
=> A structure can't be abstract.
=> No need to create object by new keyword.
=> Do not have permission to create any default constructor.
=> A structure couldn't be null.
=> A structure couldn't have a destructor.
=> Fields are not initialized with structures to 0/false/null.

Class:
------
=> The class is reference type in C# and it inherits from the System.Object Type.
=> Classes are usually used for large amounts of data.
=> Classes can be inherited to other class.
=> A class can be abstract type.
=> We can�t use an object of a class with using new keyword.
=> We can create a default constructor.
=> A class could be null.
=> A class could have a destructor.
=> Fields are automatically initialized with classes to 0/false/null.
===================================================================================
==================================
WHAT IS ENUM IN C#?
=> The enum keyword is used to declare an enumeration, a distinct type that
consists of a set of named constants called the enumerator list.
=> Usually it is best to define an enum directly within a namespace so that all
classes in the namespace can access it with equal convenience. However, an enum can
also be nested within a class or struct. 1
=> By default, the first enumerator has the value 0, and the value of each
successive enumerator is increased by 1. For example, in the following enumeration,
Sat is 0, Sun is 1, Mon is 2, and so forth.

Example:-
---------
enum Days {Sat, Sun, Mon, Tue, Wed, Thu, Fri};

Every enumeration type has an underlying type, which can be any integral type
except char. The default underlying type of enumeration elements is int. To declare
an enum of another integral type, such as byte, use a colon after the identifier
followed by the type, as shown in the following example.

enum Days : byte {Sat=1, Sun, Mon, Tue, Wed, Thu, Fri};
The approved types for an enum are byte, sbyte, short, ushort, int, uint, long, or
ulong.
Example:-
---------
public class GetValuesTest {
enum Colors { Red, Green, Blue, Yellow };
enum Styles { Plaid = 0, Striped = 23, Tartan = 65, Corduroy = 78 };

public static void Main() {

Console.WriteLine("The names of the Colors Enum are:");


foreach (string str in Enum.GetNames(typeof(Colors)))
Console.WriteLine(str);

Console.WriteLine();

Console.WriteLine("The values of the Styles Enum are:");


foreach(int i in Enum.GetValues(typeof(Styles)))
Console.WriteLine(i);
}
}

// The example produces the following output:


// The values of the Colors Enum are:
// 0
// 1
// 2
// 3
//
// The values of the Styles Enum are:
// 0
// 23
// 65
// 78

Some points about enum:


-----------------------
--Enums are enumerated data type in c#.
--Enums are not for end-user, they are meant for developers.
--Enums are strongly typed constant. They are strongly typed, i.e. an enum of one
type may not be implicitly assigned to an enum of another type even though the
underlying value of their members are the same.
--Enumerations (enums) make your code much more readable and understandable.
--Enum values are fixed. Enum can be displayed as a string and processed as an
integer.
--The default type is int, and the approved types are byte, sbyte, short, ushort,
uint, long, and ulong.
--Every enum type automatically derives from System.Enum and thus we can use
System.Enum methods on enums.
--Enums are value types and are created on the stack and not on the heap.

When to use Enum:-


------------------
If a program uses a set of integral numbers, consider replacing them with enums,
which makes the program more Readable, Maintainable.
===================================================================================
==================================
WHAT ARE THE DIFFERENCE BETWEEN BREAK AND CONTINUE IN C#?
Using break statement, you can 'jump out of a loop' whereas by
using continue statement, you can 'jump over one iteration' and then resume your
loop execution.
===================================================================================
==================================
WHAT IS DIFFERENCE BETWEEN DISPOSE() AND FINALIZE() METHODS IN C# ?
Finalizer and dispose both are used for same task like to free unmanaged resources
but have some differences.
Finalize:
---------
-Finalize used to free unmanaged resources those are not in use like files,
database connections in application domain and more, held by an object before that
object is destroyed.
-In the Internal process it is called by Garbage Collector and can�t called manual
by user code or any service.
-Finalize belongs to System.Object class.
-Implement it when you have unmanaged resources in your code, and make sure that
these resources are freed when the Garbage collection happens.

Dispose:
---------
-Dispose is also used to free unmanaged resources those are not in use like files,
database connections in Application domain at any time.
-Dispose explicitly it is called by manual user code.
-If we need to dispose method so must implement that class by IDisposable
interface.
-It belongs to IDisposable interface.
-Implement this when you are writing a custom class that will be used by other
users.
===================================================================================
==================================
WHAT ARE THE DIFFERENE BETWEEN STRING AND STRING BUILDER?
String:
-------
String is immutable(Non updatable). It means that you can't modify string at all,
the result of modification is new string. This is not effective if you plan to
append to string.

Example:-
---------
string str = string.Empty;
for (int i = 0; i < 1000; i++)
{
str += i.ToString() + "";// creates a new instance for every iteration
}
// You'll end up creating 2001 strings here, 2000 of which are thrown away.

String Builder:
----------------
StringBuilder is mutable(Updatable). It can be modified in any way and it doesn't
require creation of new instance. When work is done, ToString() can be called to
get the string.

Example:-
----------
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 1000; i++)
{
sb.Append(i);
sb.Append(' ');
}
// This should place much less stress on the memory allocator.
The final effect is the same, but the StringBuilder will use less memory and will
run faster. Instead of creating a new string which is the concatenation of the two,
it will create the chunks separately, and only at the end it will unite them.

If you make a lot of string operations like appending,truncating then StringBuilder


is a good option.

Differences:-
-------------
String:
-------
--It�s an immutable
--Performance wise string is slow because every time it will create new instance
--In string we don�t have append keyword
--String belongs to System namespace

StringBuilder:-
---------------
--It�s mutable
--Performance wise stringbuilder is high because it will use same instance of
object to perform any action
--In StringBuilder we can use append keyword
--Stringbuilder belongs to System.Text namespace
===================================================================================
==================================
WHAT ARE THE DIFFERENCES BETWEEN EQUAL() AND == METHODS IN C#?
Both the == Operator and the Equals() method are used to compare two value type
data items or reference type data items. The == Operator compares the reference
identity while the Equals() method compares only contents.

In this example we assigned a string variable to another variable. A string is a


reference type and in the following example, a string variable is assigned to
another string variable so they are referring to the same identity in the heap and
both have the same content so you get True output for both the == Operator and the
Equals() method.

namespace ComparisionExample {
class Program {
static void Main(string[] args) {
string name = "sandeep";
string myName = name;
Console.WriteLine("== operator result is {0}", name == myName);
Console.WriteLine("Equals method result is {0}", name.Equals(myName));

Console.ReadKey();
}
}
}

Key Points:-
------------
=> '==' comapres object references.
=> '.Equals()' compares object contents.
=> string datatypes always does content comparison.
===================================================================================
==================================
WHAT ARE THE DIFFERENCE BETWEEN IS AND AS OPERATOR IN C#?
"is" operator:-
---------------
In the C# language, we use the "is" operator to check the object type. If the two
objects are of the same type, it returns true and false if not.

Example:
class Speaker {
public string Name {get; set;}
}
class Author {
public string Name {get; set;}
}
var author = new Author { Name = "Gaurav Kumar Arora" };
var isTrue = speaker is Author;
Console.WriteLine("speaker is of Author type:{0}", isTrue);
output: False

"as" operator:-
---------------
The "as" operator behaves similar to the "is" operator. The only difference is it
returns the object if both are compatible to that type else it returns null.

Example:-
public static string GetAuthorName(dynamic obj)
{
Author authorObj = obj as Author;
return (authorObj != null) ? authorObj.Name : string.Empty;
}
===================================================================================
==================================
HOW TO USE NULLABLE TYPE IN C#?
A nullable Type is a data type is that contain the defined data type or the value
of null.
This nullable type concept is not comaptible with "var".

Example:-
int? i = null;
===================================================================================
==================================
WHAT IS VIRTUAL METHOD IN C#?
->A virtual method is a method that can be defined in the base class and redefined
in derived classes.
->A virtual method has an implementation in a base class as well as derived class.
It is used when a method's basic functionality is the same but sometimes more
functionality is needed in the derived class.
->A virtual method is created in the base class that can be overridden in the
derived class. We create a virtual method in the base class using the virtual
keyword and that method is overridden in the derived class using the override
keyword.

When a method is declared as a virtual method in a base class then that method can
be optional for the derived class to override that method.

KeyPoints:
----------
By default, methods are non-virtual. We can't override a non-virtual method.
We can't use the virtual modifier with the static, abstract, private or override
modifiers.
===================================================================================
==================================
WHAT IS VIRTUAL KEYWORD?
The virtual keyword is used to modify a method, property, indexer, or event
declaration and allow for it to be overridden in a derived class. For example, this
method can be overridden by any class that inherits it:

public virtual double Area()


{
return x * y;
}
The implementation of a virtual member can be changed by an overriding member in a
derived class.
===================================================================================
==================================
WHAT IS ARRAY? AND WHAT IS JAGGED ARRAY IN C#?
Array:-
-------
->Array as a collection of items of the same type stored at continuous memory
locations.
->An array index starts at zero. That means the first item of an array starts at
the 0th position. The position of the last item on an array will total number of
items - 1.

Array Overview:-
----------------
=> An array can be Single-Dimensional, Multidimensional or Jagged.
=> The number of dimensions and the length of each dimension are established when
the array instance is created. These values can't be changed during the
lifetime of the instance.
=> The default values of numeric array elements are set to zero, and reference
elements are set to null.
=> A jagged array is an array of arrays, and therefore its elements are reference
types and are initialized to null.
=> Arrays are zero indexed: an array with n elements is indexed from 0 to n-1.
=> Array elements can be of any type, including an array type.
=> Array types are reference types derived from the abstract base type Array. Since
this type implements IEnumerable and IEnumerable<T>, you can use foreach iteration
on all arrays in C#.

Jagged Arrays:-
---------------
Jagged arrays are array of arrays. The elements of a jagged array are other arrays.
The elements of a jagged array can be of different dimensions and sizes. A jagged
array is sometimes called an "array of arrays."
A special type of array is introduced in C#. A Jagged Array is an array of an
arrays in which the length of each array index can differ.

Example:-
int[][] jagArray = new int[2][];

jaggedArray[0] = new int[3];


jaggedArray[1] = new int[5];

jaggedArray[0] = new int[] { 3, 5, 7};


jaggedArray[1] = new int[] { 1, 0, 2, 4, 6 };
===================================================================================
==================================
WHAT IS ANONYMOUS TYPES IN C#?
->Anonymous types allow us to create new type without defining them.
->This is way to defining read only properties into a single object without having
to define type explicitly.
->Here Type is generating by the compiler and it is accessible only for the current
block of code. The type of properties is also inferred by the compiler.
->We can create anonymous types by using �new� keyword together with the object
initializer.

Example:-
---------
var anonymousData = new {ForeName = "Jignesh", SurName = "Trivedi"};
Console.WriteLine("First Name : " + anonymousData.ForeName);
===================================================================================
==================================
WHAT ARE THE DIFFERENCE BETWEEN VALUE TYPES AND REFERENCE TYPES IN C#?
Value type:
-----------
--Value type they are stored on stack.
--When passed as value type new copy is created and passed so changes to variable
does not get reflected back.
--Value type store real data.
--Value types are faster in access.
--Value type consists of primitive data types, structures, enumerations.
--Value types derive from System.ValueType
--Value types can not contain the value null.

Reference type:
---------------
--Reference type they are stored on heap.
--When passed as Reference type then reference of that variable is passed so
changes to variable does get reflected back.
--Reference type store reference of the data.
--Reference types are slower in access.
--Reference type consists of class, array, interface, delegates.
--Reference types derive from System.Object.
--Reference types can contain the value null.
===================================================================================
==================================
WHAT ARE THE DIFFERENCE BETWEEN STACK AND HEAP MEMORY IN C#?
stack:-
-------
--Memory will be allocated at the compile time.
--Memory is allocated by the compiler.
--Memory will be allocated only in sequential locations.
--Memory will be deleted by the compiler.
--There is lot of chance of memory wastage.

Heap Memory:
------------
--Memory will be allocated at run time.
--Memory is allocated by the user.
--Memory will be allocated in sequential and non-sequential locations.
--Memory must be deleted exlicitly by the user.
--There is no chance of memory wastge if the memory is handled perfectly.
===================================================================================
==================================
WHAT ARE THE DIFFERENCE BETWEEN METHOD OVERRIDING AND SHADOWING?
Overriding :-
-------------
->Method overriding is an important feature of OOP's that allows us to re-write a
base class function or method with a different definition. Overriding is an example
of �Dynamic polymorphism� because overriding is resolved at runtime. ->Here the
signature of the method or function must be the same. In other words both methods
(base class method and derived class method) have the same name, same number and
same type of parameter in the same order with the same return type.
->The overridden base method must be virtual, abstract or

Example:-
public class BaseClass
{
public virtual string GetMethodOwnerName()
{
return "Base Class";
}
}
public class ChildClass : BaseClass
{
public override string GetMethodOwnerName()
{
return "Child Class�;
}
}
A method cannot be overriden if:-
---------------------------------
-> Methods have a different return type
-> Methods have a different access modifier
-> Methods have a different parameter type or order
-> Methods are static or private.

Shadowing (method hiding):


--------------------------
->Hiding the definition of the base class method and gives a new definition in the
derived class method by using new keyword is called Shadowing.
->A method or function of the base class is available to the derived class without
the use of the "overriding" keyword. In the shadowing or method hiding, the derived
class has its own version of the function, the same function is also available in
the base class.

Example:-
---------
Public class BaseClass
{
public string GetMethodOwnerName()
{
return "Base Class";
}
}
public class ChildClass : BaseClass
{
public new string GetMethodOwnerName()
{
return "ChildClass";
}
}

Mixing Method (Overriding and shadowing (Method Hiding)):


---------------------------------------------------------
We can also use shadowing and method overriding together using the virtual and new
keywords. This is useful when we want to further override a method of the derived
class.
Example:-
---------
public class BaseClass
{
public virtual string GetMethodOwnerName()
{
return "Base Class";
}
}
public class ChildClass : BaseClass
{
public new virtual string GetMethodOwnerName()
{
return "ChildClass";
}
}
public class SecondChild : ChildClass
{
public override virtual string GetMethodOwnerName()
{
return "Second level Child";
}
}

Shadowing Vs Overriding:
------------------------
Shadowing is a VB.Net concept. It also known as method hiding in C#. Using this
concept we can provide a new implementation for the base class method without
overriding it.
Overriding allows us to re-write a base class function with a different definition.

Using the �new� keyword we can do the shadowing or method hiding.


C# uses the virtual/abstract and override keyword for method overriding.

Shadowing redefines an entire method or function.


Overriding redefines only the implementation of a method or function.

Showing is used to protect against subsequent base class modification.


Overriding does polymorphism by defining a different implementation.

We can change the access modifier.


We cannot change the access modifier. The access modifier must be the same as in
the base class method or function.

There is no control of a base class on shadowing. In other words, a base class


element cannot enforce or stop shadowing.
The base class has some control over the overriding. Using the keyword abstract,
the base class forces the child (derived) class to implement the function or
method.

Shadowing an element (function method or property) can be inherited further in a


child (derived) class. The shadowed element is still hidden.
The same as shadowing, overriding an element is inherited further in a derived
class and the overridden element is still overridden.

In shadowing, the base class cannot access the newly created child (derived) class
method. This is because the base class has the same name of the element.
In concept, the base class can be accessed using the child object's overridden
method.
===================================================================================
==================================
GIVE ONE REALTIME EXAMPLE FOR METHOD OVERRIDING?
The override modifier is required to extend or modify the abstract or virtual
implementation of an inherited method, property, indexer, or event.

internal class TestOverride


{
public class Employee
{
public string name;

// Basepay is defined as protected, so that it may be accessed only by


this class and derrived classes.
protected decimal basepay;
// Constructor to set the name and basepay values.
public Employee(string name, decimal basepay)
{
this.name = name;
this.basepay = basepay;
}

// Declared virtual so it can be overridden.


public virtual decimal CalculatePay()
{
return basepay;
}
}

// Derive a new class from Employee.


public class SalesEmployee : Employee
{
// New field that will affect the base pay.
private decimal salesbonus;

// The constructor calls the base-class version initializes the


salesbonus field.
public SalesEmployee(string name, decimal basepay,decimal salesbonus):
base(name, basepay)
{
this.salesbonus = salesbonus;
}

// Override the CalculatePay method to take bonus into account.


public override decimal CalculatePay()
{
return basepay + salesbonus;
}
}

private static void Main()


{
// Create some new employees.
SalesEmployee employee1 = new SalesEmployee("Alice",1000, 500);
Employee employee2 = new Employee("Bob", 1200);

Console.WriteLine("Employee4 " + employee1.name +" earned: " +


employee1.CalculatePay());
Console.WriteLine("Employee4 " + employee2.name +"earned: " +
employee2.CalculatePay());
}
}
===================================================================================
==================================
WHAT ARE EXTENSION METHODS AND HOW TO USE IT?
->Extension methods enable you to add methods to existing types without creating a
new derived type, recompiling, or otherwise modifying the original type.
->An extension method is a special kind of static method, but they are called as if
they were instance methods on the extended type.

How to use extension methods:-


-----------------------------
->An extension method is a static method of a static class, where the "this"
modifier is applied to the first parameter. The type of the first parameter will be
the type that is extended.
->Extension methods are only in scope when you explicitly import the namespace into
your source code with a using directive.

Benefits of extension methods:-


-------------------------------
->Extension methods allow existing classes to be extended without relying on
inheritance or having to change the class's source code.
->If the class is sealed than there in no concept of extending its functionality.
For this a new concept is introduced, in other words extension methods.
->This feature is important for all developers, especially if you would like to use
the dynamism of the C# enhancements in your class's design.

Important points for the use of extension methods:-


--------------------------------------------------
->An extension method must be defined in a top-level static class.
->An extension method with the same name and signature as an instance method will
not be called.
->Extension methods cannot be used to override existing methods.
->The concept of extension methods cannot be applied to fields, properties or
events.
->Overuse of extension methods is not a good style of programming.

Example:-
--------
public class NormalClass
{
public void Display()
{
Console.WriteLine("I m in Display");
}
public void Print()
{
Console.WriteLine("I m in Print");
}
}

public static class ExtensionClass


{
public static void NewMethod(this NormalClass obj)
{
Console.WriteLine("Hello I m extended method");
}
}

internal class Program


{
private static void Main(string[] args)
{
NormalClass ob = new NormalClass();
ob.Display();
ob.Print();
ob.NewMethod();
Console.ReadKey();
}
}
===================================================================================
==================================
WHAT IS PARTIAL CLASS?
-> Spliting the definition of a class or a struct or a interface or a method over
two or more source files is called as partial class.
-> Each source file contains a section of the type or method definition, and all
parts are combined when the application is compiled.

The following are some key points:


----------------------------------
->All the parts of the partial class must be prefixed with the partial keyword.
->If you seal a specific part of a partial class then the entire class is sealed,
the same as for an abstract class.
->The classes that are written in two class files are combined together at comppile
time.
->The name of each part of partial class should be the same but source file name
for each part of partial class can be different.
->Each part of a partial class should be in the same assembly or DLL, in other
words you can't create a partial class in source files of a different class library
project.
->Each part of a partial class has the same accessibility.
->If you inherit a class or interface on a partial class then it is inherited on
all parts of a partial class.

Advantages of a partial class:-


------------------------------
=> You can separate UI design code and business logic code so that it is easy to
read and understand. For example you are developing an web application using Visual
Studio and add a new web form then there are two source files, "aspx.cs" and
"aspx.designer.cs" . These two files have the same class with the partial keyword.
The ".aspx.cs" class has the business logic code while "aspx.designer.cs" has
user interface control definition.
=> When working with automatically generated source, code can be added to the class
without having to recreate the source file. Visual Studio uses this approach when
it creates Windows Forms, Web service wrapper code, and so on. You can create code
that uses these classes without having to modify the file created by Visual Studio.
=> When working on large projects, spreading a class over separate files enables
multiple programmers to work on it at the same time.
=> You can maintain your application better by compacting large classes. Suppose
you have a class that has multiple interfaces so you can create multiple source
files depending on interface implements. It is easy to understand and maintain an
interface implemented on which the source file has a partial class. Let's see the
following code snippet.

public interface IRegister


{
//Register realted function
}
public interface ILogin
{
//Login related function
}

//UserRegister.cs file
public partial classUser : IRegister, ILogin
{
//implements IRegister interface
}

//UserLogin.cs file
public partial classUser
{
//implements ILogin interface
}

Note:-
------
The partial modifier is not available on delegate or enumeration declarations.
===================================================================================
==================================
WHAT ARE THE PARTIAL METHODS IN C#?
=>A partial class or struct may contain a partial method. One part of the class
contains the signature of the method. An optional implementation may be defined in
the same part or another part.
=>If the implementation is not supplied, then the method and all calls to the
method are removed at compile time.

A partial method declaration consists of two parts: the definition and the
implementation.
These may be in separate parts of a partial class, or in the same part. If there is
no implementation declaration, then the compiler optimizes away both the defining
declaration and all calls to the method.

Example:-
----------
// Definition in file1.cs
partial void onNameChanged();

// Implementation in file2.cs
partial void onNameChanged()
{
// method body
}

The following are some key points:


----------------------------------
=>Partial method declarations must begin with the contextual keyword partial and
the method must return void.
=>Partial methods can have ref but not out parameters.
=>Partial methods are implicitly private, and therefore they cannot be virtual.
=>Partial methods cannot be extern, because the presence of the body determines
whether they are defining or implementing.
=>Partial methods can have static and unsafe modifiers.
=>Partial methods can be generic. Constraints are put on the defining partial
method declaration, and may optionally be repeated on the implementing one.
Parameter and type parameter names do not have to be the same in the implementing
declaration as in the defining one.
=>You can make a delegate to a partial method that has been defined and
implemented, but not to a partial method that has only been defined.
===================================================================================
==================================
WHAT IS DELEGATE & WHY & WHEN TO USE DELEGATE?
=>A delegate is a type safe function pointer. That means, it holds a
refernce(pointer) to a function.
=>The signature of the delegate must match the signature of the function, the
delegate points to, otherwise you get a compilation error. This is reason why
delegates are called as type safe function pointers.

A delegate is similar to a class. You can create an instance of it, and when you do
so, you pass in the function name as a parameter to the delegate constructor, and
it is to this function the delegate will point to.

Example:-
---------
public delegate void HelloFunctionDelegate(string Message);
class Program
{
public static void Main()
{
HelloFunctionDelegate del=new HelloFunctionDelegate(Hello);
del("Hello from Delegate");
}
//Method
public static void Hello(string strMessage)
{
Console.WriteLine(strMessage);
}
}

Real Time Example for using Delegate:


-------------------------------------
class Delegate
{
public static void Main()
{
List emplist = new List();
emplist.Add(new Employee() { ID = 101, Name = "Mohan", Salary = 5000, Experience =
5 });
emplist.Add(new Employee() { ID = 102, Name = "Alan", Salary = 6000, Experience = 6
});
emplist.Add(new Employee() { ID = 103, Name = "Suresh", Salary = 7000, Experience =
3 });
emplist.Add(new Employee() { ID = 104, Name = "Jay", Salary = 4000, Experience =
3 });
emplist.Add(new Employee() { ID = 105, Name = "Sachin", Salary = 4500, Experience =
3 });

IsPromotable del = new IsPromotable(Promote);

Employee.PromoteEmployee(emplist,del);
}

public static bool Promote(Employee emp)


{
if(emp.Experience >=5)
{
return true;
}
else
{
return false;
}
}

delegate bool IsPromotable(Employee empl);

class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public int Experience { get; set; }

public static void PromoteEmployee(List employeelist, IsPromotable ispromotable)


{
foreach (Employee employee in employeelist)
{
if (ispromotable(employee))
{
Console.WriteLine(employee.Name + " is promoted");
}
}
}
}

Multicast Delegates:
--------------------
A Multicast delegate is a delegate that has references to more than one function.
When you invoke a multicast delegate, all the functions the delegate is pointing
to, are invoked.
There are 2 approaches to create a multicast delegate.

Approach 1:
-----------
using System;
namespace Sample
{
public delegate void SampleDelegate();

public class Sample


{
static void Main()
{
SampleDelegate del1 = new SampleDelegate(SampleMethodOne);
SampleDelegate del2 = new SampleDelegate(SampleMethodTwo);
SampleDelegate del3 = new SampleDelegate(SampleMethodThree);
// In this example del4 is a multicast delegate. You use +(plus)
// operator to chain delegates together and -(minus) operator to
remove.
SampleDelegate del4 = del1 + del2 + del3 - del2;
del4();
}

public static void SampleMethodOne()


{
Console.WriteLine("SampleMethodOne Invoked");
}

public static void SampleMethodTwo()


{
Console.WriteLine("SampleMethodTwo Invoked");
}

public static void SampleMethodThree()


{
Console.WriteLine("SampleMethodThree Invoked");
}
}
}
If the delegate has a return type other than void and if the delegate is a
multicast delegate, only the value of the last invoked method will be returned.
Along the same lines, if the delegate has an out parameter, the value of the output
parameter, will be the value assigned by the last method.

What is the use of Delegates:-


-----------------------------
Suppose if you have multiple methods with same signature (return type & number of
parameters) and want to call all the methods with single object then we can go for
delegates.
===================================================================================
==================================
Difference between Properties and Fields?
Field:-
------
A field is a variable that is declared directly in a class or struct. Generally,
developers should use fields only for variables that have private or protected
accessibility. Fields should (most of the time) be kept private to a class and
accessed via get and set properties.

public class TestClass


{
//Here declare a field _testField, it is private to your class and stores the
actual data.
private string _testField;

//Fields should be kept private to a class and accessed via get and set
properties.
public string TestField
{
get
{
return _testField;
}
set
{
_testField = value;
}
}
}

Properties:-
------------
A property is a member that provides a flexible mechanism to read, write, or
compute the value of a private field. Properties expose fields, that means it
enable a class to expose a public way of getting and setting values, while hiding
implementation. Properties provide a level of abstraction allowing you to change
the fields while not affecting the external way they are accessed by the things
that use your class.
===================================================================================
==================================
WHAT IS ASYNCHRONOUS PROGRAMMING WITH ASYN AND AWAII?
Asynchronous Programming:-
-------------------------
Asynchronous operation means that the operation runs independent of main or other
process flow. In general c# program starts executing from the Main method and ends
when the Main method returns. In between all the operations runs sequentially one
after another. One operation must wait until its previous operation finishes. Let�s
see following code:

static void Main(string[] args)


{
DoTaskOne();
DoTaskTwo();
}
Method �DoTaskTwo� would not be started until �DoTaskOne� finishes. In other words
method �DoTaskOne� blocks the execution as long it takes to finish.
In our case if we run the �DoTaskOne� asynchronously, after calling the �DoTaskOne�
method, execution flow immediately backs to Main method and start �DoTaskTwo�.

Async:-
-------
This keyword is used to qualify a function as an asynchronous function. In other
words, if we specify the async keyword in front of a function then we can call this
function asynchronously. Have a look at the syntax of the asynchronous method.
public async void CallProcess()
{
}
Here the callProcess() method is declared as an asynchronous method because we have
declared the async keyword in front of it. Now it's ready to be called
asynchronously.

Await:-
-------
Very similar to wait, right? Yes this keyword is used when we want to call any
function asynchronously. Have a look at the following example to understand how to
use the await keyword.
Let's think; in the following we have defined a long-running process.
public static Task LongProcess()
{
return Task.Run(() =>
{
System.Threading.Thread.Sleep(5000);
});
}
Example:
--------
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

public static Task LongProcess()


{
return Task.Run(() =>
{
System.Threading.Thread.Sleep(5000);
});
}

public async void CallProcess()


{
await LongProcess();
this.listBox1.Items.Add("Long Process finish");
}

private void Form1_Load(object sender, EventArgs e)


{
}

private async void button1_Click(object sender, EventArgs e)


{
CallProcess();
this.listBox1.Items.Add("Program finish");
}
}
}
And the return type of an asynchronous function is Task. In other words, when it
finishes it's execution it will complete a Task. Each and every asynchronous method
can return three types of values.
Void: Means nothing to return
Task: It will perform one operation, a little similar to void but the difference is
there.
Task<T>: Will return a task with a T type parameter. (I hope you are familiar with
the concept of T)

KeyPoints:-
-----------
-A Main method cannot be defined as asynchronous.
-It (the Main method) cannot be invoked by the await keyword.
-If any asynchronous method is not invoked by the await keyword then by nature it
will behave like a synchronous method.
-Function properties should not be defined as asynchronous.
-The await keyword may not be inside a "lock" section.
-A try/catch block should not call any asynchronous methods from the catch or
finally block.
-A class constructor or destructor should not define an asynchronous method nor
should be called asynchronously.
===================================================================================
==================================
DIFFERENCE BETWEEN bool & Boolean AND string & String in c#?
bool & Boolean:-
----------------
Both are one and the same and both can be used. But it is recommended to use the
bool as that is the alias for the class System.Boolean.
In other words the Boolean represents the System.Boolean class while bool is the
keyword for the System.Boolean that we can use to create Boolean objects.

string & String:-


-----------------
Both are one and the same and both can be used. But it is recommended to use the
shorter version i.e. string as that is the alias for the class System.String.
In other words the String represents the System.String class while the string is
the keyword for the System.String that we can use to create string objects.
===================================================================================
==================================
DIFFERENCE BETWEEN ARRAYLIST & GENERIC LIST IN C#?
ArrayList:-
-----------
1. ArrayList belongs to the System.Collections namespace, i.e. you need to import
the following namespace.
2. ArrayList does not have type restriction for storing data i.e. it is not Type
Safe. You can store anything in ArrayList. In fact same ArrayList can store
multiple types of objects.
3. ArrayList stores all data as object thus to get it back you must remember what
you stored where and correspondingly Type Cast it as per its original Type when
stored.
4. ArrayList is mainly for .Net 2.0 Framework projects as during that period
Generic List was not invented.
5. While running a Loop on ArrayList you need to use Object data type. Thus this is
another disadvantage as you again do not know what type of data particular item
contains.

Generic Lists (List<T>):-


-------------------------
1. Generic List (List<T>) belongs to the System.Collections.Generic namespace, i.e.
you need to import the following namespace.
2. In Generic List (List<T>), T means data type, i.e. string, int, DateTime, etc.
Thus it will store only specific types of objects based on what data type has been
specified while declarations i.e. it is Type Safe. Thus if you have a Generic List
of string you can only store string values, anything else will give compilation
error.
3. Generic List stores all data of the data type it is declared thus to getting the
data back is hassle free and no type conversions required.
4. Generic List must be used instead of ArrayList unless specific requirement for
projects higher than .Net 2.0 Framework.
5. While running a Loop on Generic List again it is problem free as we exactly know
what the List contains.
===================================================================================
==================================
Q) What are Access Modifiers in C#?
In C# there are 5 different types of Access Modifiers.

Modifier Description
-----------------------------------------------------------------------------------
------------------------------
public There are no restrictions on accessing public members.
private Access is limited to the containing type.
protected Access is limited to the containing class or types derived from
the containing class.
internal Access is limited to the current assembly.
protected internal Access is limited to the current assembly or types derived
from the containing class in any other assembly.
===================================================================================
==================================
Q) What is yield keyword in C#?
The functionality this keyword provides is that when iterating a list, we can read
an element of the loop, return to the calling method code and go back to the loop
again at the same point, from where it left the loop and continue processing the
records in the loop.

Example:-
---------
public IEnumerable<Int32> GetData(List<Int32> numbersList)
{
foreach (int number in numbersList)
{
if (number > 50)
{
yield return number;
}
}
}

List<Int32> numbers = new List<int>();


numbers.Add(10); numbers.Add(20); numbers.Add(30); numbers.Add(40);
numbers.Add(50); numbers.Add(60); numbers.Add(70); numbers.Add(80);
numbers.Add(90);numbers.Add(100); numbers.Add(74); numbers.Add(77);
numbers.Add(18); numbers.Add(99); numbers.Add(33); numbers.Add(66);
numbers.Add(55); numbers.Add(63);

Program p = new Program();


IEnumerable<Int32> _IEnumerable = p.GetData(numbers);

foreach (var item in _IEnumerable)


{
Console.WriteLine(item + Environment.NewLine);
}
===================================================================================
==================================
Q) What is an Exception? Difference between System exceptions and Application
exceptions in .NET?
An Exception is an abnormal event or error condition that exists in the technical
execution of a particular statement that occurs during program execution.
Exceptions can occur in the code you write (internal) or external code (DLL) that
your program calls.

Some examples of error conditions include the following:


--------------------------------------------------------
=> File I/O related priblems
=> Network communication problems
=> Element access that is beyond the bound of an array
=> Running out of memory during program execution
=> Issue when doing a Divide-by-zero operation

CLR Exception Handling Mechanism:-


----------------------------------
When an exception occurs in a program, the .NET framework runtime handles the
problem by creating an exception object, populates it with information related to
the error and passes it on to any fault handling code. C# does not force you to use
try/catch blocks. The .NET runtime will try its best and searches a particular
fault handler from the method call stack for an exception thrown in an unprotected
block. If none is found then the .NET runtime generates an UnhandledExceptions
event.

Exception Class Hierarchy:


--------------------------
Exception
-> System Eception
-> Application Exception

Custom Exception class/Application Exception:-


----------------------------------------------
In most cases, the .NET built-in exception classes, combined with custom messages,
should meet your exception handling requirements. However, in some cases, you might
need exception types that are specific to the problem you are solving.

Sample Code Example:-


---------------------
public class NumberZeroExceptionMagic : ApplicationException
{
public NumberZeroExceptionMagic() : base() { }
// The constructor that takes msg as a parameter
public NumberZeroExceptionMagic(string msg) : base(msg) { }
}
public class Test
{
static void Main(string[] args)
{
// Prompt the user to enter an integer
Console.WriteLine("Please input an integer: ");
// Try this block of code
try
{
int Numerator = 10;
// Store the input in x
int x = Int32.Parse(Console.ReadLine());
// If the number entered is 0...
if (x == 0)
{
// ...throw our custom exception with the following message
parameter
throw new NumberZeroExceptionMagic("You are not allowed to enter
number 0");
}
Console.WriteLine("Division: " + (Numerator / x).ToString());
}
// Catch the custom exception
catch (NumberZeroExceptionMagic e)
{
// And display the error message
Console.WriteLine("Exception: " + e.Message);
}
Console.ReadLine();
}
}
Microsoft recommends that you consider the following when you design a custom
exception class:
-----------------------------------------------------------------------------------
----------
Create an exception class only if no exception class exists that satisfies your
requirement.
Derive all custom exception classes from the ApplicationException or Exception
class.

Difference between System exceptions and Application exceptions:


----------------------------------------------------------------
Application exceptions can be user defined exceptions thrown by the application.
System exceptions are common exceptions thrown by the CLR. E.g. SqlException.
System exceptions are very generic in nature and are used in almost all
applications.
===================================================================================
=================================
Q) What is the difference between throw and throws clause?
throw; rethrows the original exception and preserves its original stack trace.

throw ex; throws the original exception but resets the stack trace, destroying all
stack trace information until your catch block.

Note:-
------
NEVER write throw ex;
===================================================================================
=================================
Q) How to write texts to physical file using StreamWriter in C#?
The following example shows how StreamWriter makes it easy to write strings to a
File:

Example: Write texts to file using StreamWriter


-----------------------------------------------
//Create object of FileInfo for specified path
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");

//Open file for Read\Write


FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read );

//Create StreamWriter object to write string to FileSream


StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Another line from streamwriter");
sw.Close();
===================================================================================
=================================
Q) How to read file using StreamReader class in C#?
Use StreamReader class to read physical file in C#. The following example shows how
to read file using StreamReader.

Example: Read file using StreamReader


-------------------------------------
//Create object of FileInfo for specified path
FileInfo fi = new FileInfo(@"D:\DummyFile.txt");

//Open file for Read\Write


FileStream fs = fi.Open(FileMode.OpenOrCreate, FileAccess.Read , FileShare.Read);
//Create object of StreamReader by passing FileStream object on which it needs to
operates on
StreamReader sr = new StreamReader(fs);

//Use ReadToEnd method to read all the content from file


string fileContent = sr.ReadToEnd();

//Close StreamReader object after operation


sr.Close();
fs.Close();
===================================================================================
==================================
Q) Difference Between IEnumerable, ICollection and IList Interface in C#?
When to Use?
------------
The important point is to use the interface that our application needs us to use.

Interface Best Practices


--------------
-----------------------------------------------------------------------
IEnumerable, IEnumerable<T> The only thing you want is to iterate over the
elements in a collection.
You only need read-only access to that collection.

ICollection, ICollection<T> You want to modify the collection or you care


about its size.

IList, IList<T> You want to modify the collection and you care
about the ordering and / or positioning of the
elements in the collection.

List, List<T> As per DIP, you should depend on abstractions


instead of implementations, you should never have a
member of your own implementations with the concrete type
List/List.
===================================================================================
==================================
Q) Explain the types of comments in C#?
Single Line Comment Eg : //
Multiline Comments Eg: /* */
XML Comments Eg : ///
===================================================================================
==================================
Q) What is the difference between �finalize� and �finally� methods in C#?
=> Finalize � This method is used for garbage collection. So before destroying an
object this method is called as part of clean up activity.
=> Finally � This method is used for executing the code irrespective of exception
occurred or not.
===================================================================================
==================================
Q) Can we have only �try� block without �catch� block in C#?
No we can not have only try block without catch block.

Q) Do we get error while executing �finally� block in C#?


Yes. We may get error in finally block.

Q) Mention the assembly name where System namespace lies in C#?


Assembly Name � mscorlib.dll
===================================================================================
==================================
Q) What is the difference between methods � �System.Array.Clone()� and
�System.Array.CopyTo()� in C#?
�CopyTo()� method can be used to copy the elements of one array to other.
�Clone()� method is used to create a new array to contain all the elements which
are in the original array.
===================================================================================
==================================
Q) Explain circular reference in C#?
This is a situation where in, multiple resources are dependent on each other and
this causes a lock condition and this makes the resource to be unused.
===================================================================================
==================================
Q) What are the three types of Generic delegates in C#?
Func
Action
Predicate
===================================================================================
==================================
Q) Int32 and int are synonymous, both of them allow us to create a 32 bit integer.
int is shorthand notation (alias) for Int32. When declaring an integer in a c#
program most of us prefer using int over Int32.

Whether we use int or Int32 to create an integer, the behaviour is indentical.

int i = 10;
Int32 j = 10;

Console.WriteLine("int i = " + i);


Console.WriteLine("Int32 j = " + j);
Console.WriteLine("int i + Int32 j = " + (i + j));

I think the only place where Int32 is not allowed is when creating an enum. The
following code will raise a compiler error stating - Type byte, sbyte, short,
ushort, int, uint, long, or ulong expected.
enum Test : Int32
{ XXX = 1
}

The following code will compile just fine


enum Test : int
{ XXX = 1
}

I can think of only the following minor differences between int and Int32
1. One of the difference is in readability. When we use Int32, we are being
explicitl about the size of the variable.
2. To use Int32, either we need to use using System declaration or specify the
fully qualified name (System.Int32) where as with int it is not required

The interviewer may also ask, what is the difference between string and
System.String.
There is no difference string is an alias for System.String.
===================================================================================
==================================
Q) Can an abstract class have a constructor? If so what is the use?
Yes, an abstract class can have a constructor. In general, a class constructor is
used to initialise fields. Along the same lines, an abstract class constructor is
used to initialise fields of the abstract class. You would provide a constructor
for an abstract class if you want to initialise certain fields of the abstract
class before the instantiation of a child-class takes place. An abstract class
constructor can also be used to execute code that is relevant for every childclass.
This prevents duplicate code.

Before an instance of CorporateCustomer or SavingsCustomer class is created, a


Globally Unique Identifier (GUID) must be stored in the _id field of the abstract
class. This can be achieved using abstract class constructor as shown below. Since
initialisation is done in the base abstract Customer class, we don't have to
duplicate this logic in CorporateCustomer and SavingsCustomer classes.
public class Program
{ public static void Main() { CorporateCustomer CC = new CorporateCustomer();
Console.WriteLine(CC.Id); SavingsCustomer SC = new SavingsCustomer();
Console.WriteLine(SC.Id); }
}

public abstract class Customer


{ public Customer() { this._id = Guid.NewGuid(); } public Guid Id { get { return
this._id; } } private Guid _id; // Other abstract members // public abstract void
Save();
}

public class CorporateCustomer : Customer


{
}

public class SavingsCustomer : Customer


{
}

You cannot create an instance of an abstract class. So, what is the use of a
constructor in an abstract class?
Though you cannot create an instance of an abstract class, we can create instances
of the classes that are derived from the abstract class. So, when an instance of
derived class is created, the parent abstract class constructor is automatically
called.

Note: Abstract classes can't be directly instantiated. The abstract class


constructor gets executed through a derived class. So, it is a good practice to use
protected access modifier with abstract class constructor. Using public doesn't
make sense.
===================================================================================
==================================
Q) What is a recursive function in c#? Give an example?
A recursive function is a function that calls itself. Let's look at an example of
computing factorial of a number with and without recursion.

Program to compute factorial of a number without using recursion:


-----------------------------------------------------------------
public class Program
{
public static void Main()
{
// Prompt the user to enter a number
Console.WriteLine("Please enter a number");
// Read the number from the console and convert to int
int userNumber = Convert.ToInt32(Console.ReadLine());
// Call Factorial function and pass the user entered number to it
double factorial = Factorial(userNumber);
// Print the factorial
Console.WriteLine("Factorial of " + userNumber.ToString() + " = " +
factorial.ToString());
}

public static double Factorial(int number)


{
// ZERO factorial is 1, so return 1 if number is ZERO.
if (number == 0)
return 1;

double factorial = 1;

// Compute the factorial using a for loop


for (int i = number; i >= 1; i--)
{
factorial = factorial * i;
}

// return the factorial of the number


return factorial;
}
}

Program to compute factorial of a number with recursion.:


---------------------------------------------------------
public class Program
{
public static void Main()
{
// Prompt the user to enter a number
Console.WriteLine("Please enter a number");
// Read the number from the console and convert to int
int userNumber = Convert.ToInt32(Console.ReadLine());
// Call Factorial function and pass the user entered number to it
double factorial = Factorial(userNumber);
// Print the factorial
Console.WriteLine("Factorial of " + userNumber.ToString() + " = " +
factorial.ToString());
}

public static double Factorial(int number)


{
// ZERO factorial is 1, so return 1 if number is ZERO.
if (number == 0)
return 1;

// Notice that the Factorial method is calling itself here


return number * Factorial(number - 1);
}
}
===================================================================================
==================================
Q) Real time example of recursion?
Probably in an interview, an interviewer may ask you to give an example, where you
have used recursion in your project.
To find all the files in a folder and in all the sub-folders in the hierarchy. This
is a very good example of where we could use recursion.
// find all files in subdirectories c#.png

using System.IO;

public class Program


{
public static void Main()
{
// Prompt the user to enter folder path
Console.WriteLine("Please enter folder path");
// Read the path from the console
string folderPath = Console.ReadLine();

// Invoke FindFiles() recursive function


FindFiles(folderPath);
}

private static void FindFiles(string path)


{
// Loop thru each file in the current directory and print it's name
foreach (string fileName in Directory.GetFiles(path))
{
Console.WriteLine(fileName);
}

// If there is a subdirectory in the current directory, then recursively


// call FindFiles() method. The recursion will break when the innermost
// directory with no subdirectory is found.
foreach (string directory in Directory.GetDirectories(path))
{
// Notice that FindFiles() is calling itself
FindFiles(directory);
}
}
}
===================================================================================
==================================
Q) What are the advantages of using interfaces?
The following are the advantages of programming against interfaces over programming
against concrete classes.
1. Interfaces allow us to develop loosely coupled systems.
2. Interfaces are very useful for Dependency Injection.
3. Interfaces make unit testing and mocking easier.
===================================================================================
==================================
Q) Can you store different types in an array in c#?
Yes, if you create an object array. Here is an example. Since all types inherit
(directly or indirectly) from object type, we can add any type to the object array,
including complex types like Customer, Employee etc. You need to override the
ToString() method if you want meaningful output when ToString() method is invoked.

class Program
{
static void Main()
{
object[] objectArray = new object[3];
objectArray[0] = 101; // integer objectArray[1] = "C#"; // string Customer c = new
Customer();
c.ID = 99;
c.Name = "Pragim"; objectArray[2] = c; // Customer - Complext Type // loop thru the
array and retrieve the items foreach (object obj in objectArray)
{ Console.WriteLine(obj); } }
}

class Customer
{
public int ID { get; set; }
public string Name { get; set; }
public override string ToString() { return this.Name; }
}

Another alternative is to use ArrayList class that is present in System.Collections


namespace.
class Program
{ static void Main() { System.Collections.ArrayList arrayList = new
System.Collections.ArrayList(); arrayList.Add(101); // integer arrayList.Add("C#");
// integer Customer c = new Customer(); c.ID = 99; c.Name = "Pragim";
arrayList.Add(c); // Customer - Complext Type // loop thru the array and retrieve
the items foreach (object obj in arrayList) { Console.WriteLine(obj); } }
}
===================================================================================
==================================
Q) Difference between .net framework 4.0 and 4.5?
-> async and await (code markers)
-> Zip facility (Zip compression)
-> Regex timeout (TimeOut)
-> Profile optimization (Improved startup performance)
-> Garbage collector (GC background cleanup)
-> Array support more than two gigabyte size
<gcAllowVeryLargeObjects enabled="true" />
-> HTML 5 Support
-> Built-in mobile templates + Jquery.Mobile support in asp.net mvc.
-> Methods can access call site info as parameters(CallerInfo).
===================================================================================
==================================
Q) Complete Data About Static Keyword, Static Class, Static Member & Static
Constructor?
Static Keyword:-
----------------
-> Use the static modifier to declare a static member, which belongs to the type
itself rather than to a specific object. The static modifier can be used with
classes, fields, methods, properties, operators, events, and constructors, but it
cannot be used with indexers, destructors, or types other than classes.
-> A static member cannot be referenced through an instance. Instead, it is
referenced through the type name.
-> While an instance of a class contains a separate copy of all instance fields of
the class, there is only one copy of each static field.
-> It is not possible to use this to reference static methods or property
accessors.
-> If the static keyword is applied to a class, all the members of the class must
be static.
-> Classes and static classes may have static constructors. Static constructors are
called at some point between when the program starts and the class is instantiated.

Static Classes:-
----------------
-> A static class is basically the same as a non-static class, but there is one
difference: a static class cannot be instantiated. In other words, you cannot use
the new keyword to create a variable of the class type. Because there is no
instance variable, you access the members of a static class by using the class name
itself.

The following list provides the main features of a static class:-


-----------------------------------------------------------------
Contains only static members.
Cannot be instantiated.
Is sealed.
Cannot contain Instance Constructors.

Static Members:-
----------------
-> The static member is callable on a class even when no instance of the class has
been created. The static member is always accessed by the class name, not the
instance name. Only one copy of a static member exists, regardless of how many
instances of the class are created. Static methods and properties cannot access
non-static fields and events in their containing type, and they cannot access an
instance variable of any object unless it is explicitly passed in a method
parameter.
-> Static methods can be overloaded but not overridden, because they belong to the
class, and not to any instance of the class.
-> C# does not support static local variables (variables that are declared in
method scope).

Static Constructors:-
---------------------
-> A static constructor is used to initialize any static data, or to perform a
particular action that needs to be performed once only. It is called automatically
before the first instance is created or any static members are referenced.

Static constructors have the following properties:-


---------------------------------------------------
-> A static constructor does not take access modifiers or have parameters.
-> A static constructor is called automatically to initialize the class before the
first instance is created or any static members are referenced.
-> A static constructor cannot be called directly.
-> The user has no control on when the static constructor is executed in the
program.
-> A typical use of static constructors is when the class is using a log file and
the constructor is used to write entries to this file.
-> Static constructors are also useful when creating wrapper classes for unmanaged
code, when the constructor can call the LoadLibrary method.
-> If a static constructor throws an exception, the runtime will not invoke it a
second time, and the type will remain uninitialized for the lifetime of the
application domain in which your program is running.
===================================================================================
==================================
Q) What is the difference between loose coupling and tight coupling in the object
oriented paradigm?
-> Tight coupling is when a group of classes are highly dependent on one another.
-> This scenario arises when a class assumes too many responsibilities, or when one
concern is spread over many classes rather than having its own class.

-> Loose coupling is achieved by means of a design that promotes single-


responsibility and separation of concerns.
A loosely-coupled class can be consumed and tested independently of other
(concrete) classes.
Interfaces are a powerful tool to use for decoupling. Classes can communicate
through interfaces rather than other concrete classes, and any class can be on the
other end of that communication simply by implementing the interface.

Example of tight coupling:-


---------------------------
class CustomerRepository
{
private readonly Database database;

public CustomerRepository(Database database)


{
this.database = database;
}

public void Add(string CustomerName)


{
database.AddRow("Customer", CustomerName);
}
}

class Database
{
public void AddRow(string Table, string Value)
{
}
}

Example of loose coupling:-


---------------------------
class CustomerRepository
{
private readonly IDatabase database;

public CustomerRepository(IDatabase database)


{
this.database = database;
}

public void Add(string CustomerName)


{
database.AddRow("Customer", CustomerName);
}
}

interface IDatabase
{
void AddRow(string Table, string Value);
}

class Database : IDatabase


{
public void AddRow(string Table, string Value)
{
}
}
===================================================================================
==================================
Q) C Sharp Anonymous Method?
-> The concept of anonymous method was introduced in C# 2.0.
-> An anonymous method is inline unnamed method in the code. It is created using
the delegate keyword and doesn�t required name and return type.
-> Hence we can say, an anonymous method has only body without name, optional
parameters and return type.
-> An anonymous method behaves like a regular method and allows us to write inline
code in place of explicitly named methods.

A Simple Anonymous Method Example:-


-----------------------------------
delegate int MathOp(int a, int b);
class Program
{
//delegate for representing anonymous method
delegate int del(int x, int y);

static void Main(string[] args)


{
//anonymous method using delegate keyword
del d1 = delegate(int x, int y) { return x * y; };

int z1 = d1(2, 3);

Console.WriteLine(z1);
}
}
//output:
6

Key points about anonymous method:-


-----------------------------------
-> A variable, declared outside the anonymous method can be accessed inside the
anonymous method.
-> A variable, declared inside the anonymous method can�t be accessed outside the
anonymous method.
-> We use anonymous method in event handling.
-> An anonymous method, declared without parenthesis can be assigned to a delegate
with any signature.
-> Unsafe code can�t be accessed within an anonymous method.
-> An anonymous method can�t access the ref or out parameters of an outer scope.
=======================================================COMPLETED===================
==================================

===================================================================================
==================================
ADO.NET:
========

DIFFERENCE BETWEEN DATAREADER, DATASET, DATAADAPTER & DATATABLE IN C#?


DATA READER:-
-------------
->DataReader as the name suggests reads data. DataReader is used for fetching
records from the SQL Query or Stored Procedure i.e. SELECT Operation.
->DataReader is the fastest technique to fetch records from database and it works
only in Forward direction meaning a row read once cannot be read again.
->DataReader is ReadOnly and it fetches only one row at a time in memory and hence
it has less load on memory.
->The Read function of the DataReader reads one row at a time in memory and if a
row is read then the function returns True else False.
->DataReader requires an open connection in order to execute the SQL statement, and
this feature is termed as Connected Architecture.
->Example would be fetching Name City for all records in the Person Table using
DataReader.

string constring =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, City FROM Persons", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if(dr.HasRowa)
{
while (dr.Read())
{
string name = dr["Name"].ToString();
string city = dr["City"].ToString();
Response.Write("Name: " + name);
Response.Write("City: " + city);
}
}
con.Close();
}
}

DATA ADAPTER:-
--------------
->DataAdapter is used to execute SQL statements and is used to populate the results
of SQL Query into a DataSet or DataTable.
->DataAdapter gets all the rows of the executed SQL statement at once and populates
into DataSet or DataTable in memory and hence DataAdapter is bit slower compared
to DataReader.
->Since the DataAdapter populates all rows in DataSet or DataTable it can be
traversed in both Forward and Backward directions.
->DataAdapter makes use of the Fill function to populate the rows of SQL statement
into a DataSet or DataTable.
->DataAdapter manages the connection internally and does not require to open or
close connections explicitly and this feature is termed as Disconnected
Architecture.
->Example would be fetching Name City for all records in the Person Table using
DataAdapter.

string constring =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, City FROM Persons", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
sda.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
string name = row["Name"].ToString();
string city = row["City"].ToString();
Response.Write("Name: " + name);
Response.Write("City: " + city);
}
}
}
}

DATA SET:-
----------
->DataSet is in simple terms set of Data i.e. set of DataTables or collection of
DataTables i.e. it can hold one or multiple DataTables.
->DataSet is mainly used to fetch and hold the records for one or more tables into
memory.
->A DataAdapter is used to populate DataSet from records returned from an SQL
statement and also a DataSet can be created in memory and tables and data can be
added to it.
->DataSet can also be converted and saved as XML file.
->Example would be fetching Name City for all records in the Person Table into a
DataSet.

string constring =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, City FROM Persons", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataSet ds = new DataSet();
sda.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
string name = row["Name"].ToString();
string city = row["City"].ToString();
Response.Write("Name: " + name);
Response.Write("City: " + city);
}
}
}
}

DATA TABLE:-
------------
->A DataTable can hold records of a single Table consisting of rows and columns. A
DataTable can be reside within a DataSet.
->DataTable is mainly used to fetch and hold the records of one single table into
memory.
->A DataAdapter is used to populate DataTable from records returned from an SQL
statement and also a DataTable can be created in memory and data can be added to
it.
->Example would be fetching Name City for all records in the Person Table into a
DataTable.

string constring =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, City FROM Persons", con))
{
cmd.CommandType = CommandType.Text;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
DataTable dt = new DataTable();
sda.Fill(dt);
foreach (DataRow row in dt.Rows)
{
string name = row["Name"].ToString();
string city = row["City"].ToString();
Response.Write("Name: " + name);
Response.Write("City: " + city);
}
}
}
}
===================================================================================
==================================
DIFFERENCE BETWEEN EXECUTENONQUERY, EXECUTESCALAR & EXECUTEREADER IN C#?
EXECUTENONQUERY():-
-------------------
->ExecuteNonQuery is basically used for operations where there is nothing returned
from the SQL Query or Stored Procedure. Preferred use will be for INSERT, UPDATE
and DELETE Operations.
->The ExecuteNonQuery returns the rows affected value.
string name = "Mudassar Khan";
string city = "Pune";
string constring =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Persons (Name, City) VALUES
(@Name, @City)", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@City", city);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
}

What happens when I use ExecuteNonQuery for SELECT statement?


-------------------------------------------------------------
->ExecuteNonQuery will work flawlessly for SELECT SQL Query or Stored Procedure but
that will simply execute the query and do nothing. Even if you use it you will not
throw any error but the Rows Affected will be negative i.e. -1.

string constring =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Persons", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@City", city);
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
}
}
Thus concluding it, we must use ExecuteNonQuery for INSERT, UPDATE and DELETE
operations only.

EXECUTESCALAR():-
-----------------
->ExecuteScalar is a handy function when you want to just need one Cell value i.e.
one column and one row.
For example in a case where I need to get the City of a person based on its Name.
->The ExecuteScalar returns the value of the column returned.

string name = "Mudassar Khan";


string constring =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT City FROM Persons WHERE
Name=@Name", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
con.Open();
object o = cmd.ExecuteScalar();
if (o != null)
{
string city = o.ToString();
}
con.Close();
}
}

What happens when I use ExecuteScalar for SELECT statement with multiple columns
and multiple rows?
-----------------------------------------------------------------------------------
----------------
This is a great question and the answer is yes you can use it but as its behavior
it will return the very first cell i.e. first row and first column.

using (SqlConnection con = new SqlConnection(constring))


{
using (SqlCommand cmd = new SqlCommand("SELECT Name, City FROM Persons WHERE
Name=@Name", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
con.Open();
object o = cmd.ExecuteScalar();
if (o != null)
{
string city = o.ToString();
}
con.Close();
}
}
It returns the value of the first cell i.e. first row and first column being
returned.

Can we use ExecuteScalar for INSERT, UPDATE and DELETE Statements?


------------------------------------------------------------------
Yes you can. But since INSERT, UPDATE and DELETE Statements return no value you
will not get any value returned from the Query as well as you will not get the Rows
Affected like you get in ExecuteNonQuery.

string name = "Mudassar Khan";


string city = "Pune";
string constring =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("UPDATE Persons SET City = @City WHERE
Name = @Name", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@City", city);
con.Open();
object o = cmd.ExecuteScalar();
con.Close();
}
}
It returned value being returned as NULL since there�s nothing returned from the
UPDATE query.
Thus concluding it, we must use ExecuteScalar must be when used when you need to
fetch a single cell (Scalar) value.

EXECUTEREADER():-
-----------------
->ExecuteReader is strictly used for fetching records from the SQL Query or Stored
Procedure i.e. SELECT Operation.
Example would be fetching Name City for all records in the Person Table.

string constring =
ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, City FROM Persons", con))
{
cmd.CommandType = CommandType.Text;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
string name = dr["Name"].ToString();
string city = dr["City"].ToString();
Response.Write("Name: " + name);
Response.Write("City: " + city);
}
con.Close();
}
}
===================================================================================
==================================
WHAT IS THE DIFFERENCE BETWEEN DATAREADER AND DATASET IN C#?
Datareader:-
------------
=> Forward only
=> Connected Recordset
=> Single table involved
=> No relationship required
=> No XML storage
=> Occupies Less Memory
=> Read only

Dataset:-
---------
=> Loop through Dataset
=> Disconnected Recordset
=> Multiple tables involved
=> Relationship between tables maintained
=> Can be stored as XML
=> Occupies More memory
=> Can do addition / Updation and Deletion
===================================================================================
==================================
What is the default Timeout for SqlCommand.CommandTimeout property?
The default timeout of Sqlcommand. CommandTimeout property is 30 Seconds.
===================================================================================
==================================
What are the uses of Stored Procedure?
=> Improved Performance.
=> Easy to use and maintain.
=> Security.
=> Less time and effort taken to execute.
=> Less Network traffic.
===================================================================================
==================================
What is the difference between Dataset.clone and Dataset.copy?
=> Dataset.clone object copies structure of the dataset including schemas,
relations and constraints. This will not copy data in the table.
=> Dataset.copy � Copies both structure and data from the table.
===================================================================================
==================================
HOW TO INSERT BULK RECORDS INTO DATABASE USING C#?
SqlBulkCopy as the name suggest is for copying (inserting) bulk records and it
cannot perform update operation. Hence comes Table Valued Parameter to the rescue,
which allows us to pass multiple records using a DataTable to a Stored Procedure
where we can do the processing.

Example Code:-
--------------
private void BulkInsertToDataBase()
{
DataTable dtProductSold = (DataTable)ViewState["ProductsSold"];
connection();

//creating object of SqlBulkCopy


SqlBulkCopy objbulk = new SqlBulkCopy(con);

//assigning Destination table name


objbulk.DestinationTableName = "ProdcutsSold";

//Mapping Table column


objbulk.ColumnMappings.Add("ProductName", "ProductName");
objbulk.ColumnMappings.Add("BrandName", "BrandName");
objbulk.ColumnMappings.Add("Warrenty", "Warrenty");
objbulk.ColumnMappings.Add("Price",

//inserting bulk Records into DataBase


objbulk.WriteToServer(dtProductSold);
}
===================================================================================
==================================
What is Table-Valued Parameters in SQL?
Table Valued Parameter is a new feature introduced with SQL Server 2008. Table
Valued Parameters help to pass multiple rows of data from a client application to
SQL Server without multiple round trips. Using a Table Valued Parameter we can pass
multiple rows to a stored procedure.

Table Valued Parameter is a mechanism to pass bulk data from ADO.NET to SQL Server.
In the following example we learn how to pass a Table Valued Parameter to a stored
procedure. Using a Table Valued Parameter, we can pass a table as a single object
instead of row by row.

Step 1: Create a table and a User Defined table type:

CREATE TABLE CUSTOMER


(
CustomerId INT NOT NULL,
CustomerName VARCHAR(MAX),
Isdeleted BIT,
PRIMARY KEY (CustomerId)
)

CREATE TYPE dbo.TableValuedTypeExample AS TABLE


(
CustomerId INT NOT NULL,
CustomerName VARCHAR(MAX),
PRIMARY KEY (CustomerId)
)

Now create a procedure to receive data for the Table Valued Parameter and insert it
into our original table:

CREATE PROC InsertValue


(@TempTable AS dbo.TableValuedTypeExample READONLY)
AS
BEGIN
INSERT INTO CUSTOMER (CustomerId,CustomerName ,Isdeleted )
SELECT CustomerId, CustomerName, 0 AS Isdeleted FROM @TempTable
END

Step 2: Create a DataTable or structure the same as your Table Valued Parameter.
Remember that all columns of the DataTable are parallel to the Table Data type:

static DataTable CreateTable()


{
DataTable dt = new DataTable();
dt.Columns.Add("CustomerId", typeof(Int32));
dt.Columns.Add("CustomerName", typeof(string));
return dt;
}

Step 3: To pass the data to the stored procedure, it must be represented as a


SqlParameter and the type of this parameter must be structured:

//Create Table
DataTable myTable = CreateTable();

// Add New Rowto table


myTable.Rows.Add(1, "Jignesh Trivedi");
myTable.Rows.Add(2, "Tejas Trivedi");
myTable.Rows.Add(3, "Rakesh Trivedi");

SqlConnection connection = new SqlConnection("Data Source= DatabaseName;Initial


Catalog=AdventureWorks;User
Id=sa;Password=password;");
connection.Open();
SqlCommand cmd = new SqlCommand("InsertValue", connection);
cmd.CommandType = CommandType.StoredProcedure;

//Pass table Valued parameter to Store Procedure


SqlParameter sqlParam = cmd.Parameters.AddWithValue("@TempTable", myTable);
sqlParam.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();
connection.Close();
Console.Write("Data Save Successfully.");

Step 4: You can also do this using a generic list. Here the myDataCollection class
is inherited from the List<myData> class and
the IEnumerable<SqlDataRecord> interface. The implementation IEnumerable
<SqlDataRecord> will be used to convert our List data to our user
defined table:

public class myData


{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
}

public class myDataCollection : List<myData>, IEnumerable<SqlDataRecord>


{
IEnumerator<SqlDataRecord> IEnumerable<SqlDataRecord>.GetEnumerator()
{
SqlDataRecord ret = new SqlDataRecord(
new SqlMetaData("CustomerId", SqlDbType.Int),
new SqlMetaData("CustomerName", SqlDbType.VarChar, 20)
);

foreach (myData data in this)


{
ret.SetInt32(0, data.CustomerId);
ret.SetString(1, data.CustomerName);
yield return ret;
}
}
}
myDataCollection myTable = new myDataCollection();
myTable.Add(new myData { CustomerId = 4, CustomerName = "Jignesh" });
myTable.Add(new myData { CustomerId = 5, CustomerName = "Tejas" });
myTable.Add(new myData { CustomerId = 6, CustomerName = "Rakesh" });

SqlConnection connection = new SqlConnection("Data Source= DatabaseName;Initial


Catalog=AdventureWorks;User
Id=sa;Password=password;");
connection.Open();
SqlCommand cmd = new SqlCommand("InsertValue", connection);
cmd.CommandType = CommandType.StoredProcedure;

//Pass table Valued parameter to Store Procedure


SqlParameter sqlParam = cmd.Parameters.AddWithValue("@TempTable", myTable);
sqlParam.SqlDbType = SqlDbType.Structured;
cmd.ExecuteNonQuery();
connection.Close();
Console.Write("Data Save Successfully.");
===================================================================================
==================================
Q) Display database table metadata in asp net web application?
Step 1: Use the following SQL script to create database tables.

Create table Departments


(
ID int primary key identity,
Name nvarchar(50),
Location nvarchar(50)
)

Create table Employees


(
ID int primary key identity,
FirstName nvarchar(50),
LastName nvarchar(50),
Gender nvarchar(50),
Salary int,
DepartmentId int foreign key references Departments(Id)
)

Step 2: Stored procedures to retrieve the list of table names and their metadata.
Create Procedure spGetAllTables
as
Begin
Select TABLE_NAME
from INFORMATION_SCHEMA.TABLES
where TABLE_TYPE='BASE TABLE'
End

Create Procedure spGetTableMetaData


@TableName nvarchar(50)
as
Begin
Select COLUMN_NAME, DATA_TYPE
from INFORMATION_SCHEMA.COLUMNS
where TABLE_NAME = @TableName
End
Step 3: Create an asp.net web application. Drag and drop a DropDownList control.
a) Set AutoPostBack="true"
b) Double click on the DropDownList1 control to generate the click event handler.

At this point the HTML for the DropDownList should look as shown below.
<asp:DropDownList ID="DropDownList1" AutoPostBack="true" runat="server"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>

Step 4: Drag and drop a GridView control and AutoFormat it to select "Colourful"
scheme. Add 2 bound columns
a) For the first bound column set
DataField="Column_Name"
HeaderText="Column Name"
b) For the second bound column set
DataField="Data_Type"
HeaderText="Data Type"
c) Set AutoGenerateColumns="False"

At this point the HTML for the GridView should look as shown below.
<asp:GridView ID="GridView1" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None"
AutoGenerateColumns="False"
EnableViewState="False">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="Column_Name" HeaderText="Column Name" />
<asp:BoundField DataField="Data_Type" HeaderText="Data Type" />
</Columns>
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<SortedAscendingCellStyle BackColor="#FDF5AC" />
<SortedAscendingHeaderStyle BackColor="#4D0000" />
<SortedDescendingCellStyle BackColor="#FCF6C0" />
<SortedDescendingHeaderStyle BackColor="#820000" />
</asp:GridView>

Step 5: Copy and paste the following code in the code-behind file.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI.WebControls;

namespace DemoTables
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DropDownList1.DataTextField = "TABLE_NAME";
DropDownList1.DataValueField = "TABLE_NAME";
DropDownList1.DataSource = GetAllTables();
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, new ListItem("Select Table", "-1"));
}
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs


e)
{
if (DropDownList1.SelectedValue != "-1")
{
GridView1.DataSource =
GetTableMetadata(DropDownList1.SelectedValue);
GridView1.DataBind();
}
}

private DataTable GetAllTables()


{
string CS =
ConfigurationManager.ConnectionStrings["SampleDBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlDataAdapter da = new SqlDataAdapter("spGetAllTables", con);
DataTable dataTable = new DataTable();
da.Fill(dataTable);

return dataTable;
}

private DataTable GetTableMetadata(string tableName)


{
string CS =
ConfigurationManager.ConnectionStrings["SampleDBCS"].ConnectionString;
SqlConnection con = new SqlConnection(CS);
SqlDataAdapter da = new SqlDataAdapter("spGetTableMetadata", con);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add(new SqlParameter("@TableName",
tableName));
DataTable dataTable = new DataTable();
da.Fill(dataTable);

return dataTable;
}
}
}
===================================================================================
==================================
Q) How to retrieve data from different databases in asp net?
SQL Script to
1. Create USADB and UKDB Databases
2. Create Employees table in both the databases
3. Populate Employees table in both the databases

Create Database USADB


GO

Create Database UKDB


GO

USE USADB
GO

Create table Employees


(
ID int primary key,
FirstName nvarchar(50),
LastName nvarchar(50),
Gender nvarchar(50),
Salary int,
Country nvarchar(50)
)

Insert into Employees values (1, 'Mark', 'Hastings', 'Male', 60000, 'USA')
Insert into Employees values (2, 'Steve', 'Pound', 'Male', 45000, 'USA')
Insert into Employees values (3, 'Ben', 'Hoskins', 'Male', 70000, 'USA')
Insert into Employees values (4, 'Philip', 'Hastings', 'Male', 45000, 'USA')

USE UKDB
GO

Create table Employees


(
ID int primary key,
FirstName nvarchar(50),
LastName nvarchar(50),
Gender nvarchar(50),
Salary int,
Country nvarchar(50)
)

Insert into Employees values (5, 'Mary', 'Lambeth', 'Female', 30000, 'UK')
Insert into Employees values (6, 'Valarie', 'Vikings', 'Female', 35000, 'UK')
Insert into Employees values (7, 'John', 'Stanmore', 'Male', 80000, 'UK')

Create a new empty asp.net web application.

Copy and paste the following 2 connection strings in web.config file.


<connectionStrings>
<add name="USADB" connectionString="server=.;
database=USADB; integrated security=true"/>
<add name="UKDB" connectionString="server=.;
database=UKDB; integrated security=true"/>
</connectionStrings>

Add a webform to the project. Drag and drop a GridView control on the webform. Copy
and paste the following code in the code-behind file.
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace Demo
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string USADBCS =
ConfigurationManager.ConnectionStrings["USADB"].ConnectionString;
string UKDBCS =
ConfigurationManager.ConnectionStrings["UKDB"].ConnectionString;
SqlConnection con = new SqlConnection(USADBCS);
SqlDataAdapter da = new SqlDataAdapter("select * from Employees", con);

DataSet ds1 = new DataSet();


da.Fill(ds1);

con = new SqlConnection(UKDBCS);


da.SelectCommand.Connection = con;

DataSet ds2 = new DataSet();


da.Fill(ds2);

ds1.Merge(ds2);

GridView1.DataSource = ds1;
GridView1.DataBind();
}
}
}
===================================================================================
==================================
Q) What is Connection Pooling in ADO.NET?
Connection pooling is the ability of reusing your connection to the database. This
means if you enable Connection pooling in the connection object, actually you
enable the re-use of the connection to more than one user.

ADO.NET uses a technique called connection pooling, which minimizes the cost of
repeatedly opening and closing connections. Connection pooling reuses existing
active connections with the same connection string instead of creating new
connections when a request is made to the database. It involves the use of a
connection manager that is responsible for maintaining a list, or pool, of
available connections for a given connection string. Several pools exist if
different connection strings ask for connection pooling.

Example of Pooling:
-------------------
connection.ConnectionString = sqlConnectString + "Connection Timeout=30;Connection
Lifetime=0;Min Pool Size=0;Max Pool Size=100;Pooling=true;";
//Open connection
A Connection String in the Web.Config file with connection pooling option:
<connectionStrings>
<clear />
<add name="sqlConnectionString" connectionString="Data
Source=mySQLServer;Initial Catalog=myDatabase;Integrated Security=True;Connection
Timeout=15;Connection Lifetime=0;Min Pool Size=0;Max Pool
Size=100;Pooling=true;" />
</connectionStrings>

SQL Server connection string pooling attributes:


------------------------------------------------
Connection Lifetime:
Length of time in seconds after creation after which a connection is destroyed. The
default is 0, indicating that connection will have the maximum timeout.

Connection Reset:
Specifies whether the connection is reset when removed from the pool. The default
is true.
Enlist:
Specifies whether the connection is automatically enlisted in the current
transaction context of the creation thread if that transaction context exists. The
default is true.

Load Balance Timeout:


Length of time in seconds that a connection can remain idle in a connection pool
before being removed.

Max Pool Size:


Maximum number of connections allowed in the pool. The default is 100.

Min Pool Size:


Minimum number of connections maintained in the pool. The default is 0.

Pooling: When true, the connection is drawn from the appropriate pool, or if
necessary, created and added to the appropriate pool. The default is true.
========================================================COMPLETED==================
==================================

===================================================================================
==================================
ASP.NET:
========

What is a postback?
All the web applications are running on Web Servers. Whenever a user made a request
to the web server, the web server has to return the response to the user. PostBack
is the name given to the process of submitting all the information that the user is
currently working on and send it all back to the server. Postback is actually
sending all the information from client to web server, then web server process all
those contents and returns back to client.

Example:-
---------
if (!IsPostback)
// generate dynamic form
else
process submitted data;
===================================================================================
==================================
What is IsPostBack?
IsPostBack is a Page level property, that can be used to determine whether the page
is being loaded in response to a client postback, or if it is being loaded and
accessed for the first time.

Is Postback is normally used on page _load event to detect if the web page is
getting generated due to postback requested by a control on the page or if the page
is getting loaded for the first time.

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
// generate form;
}
else
{
//process submitted data;
}
}
===================================================================================
==================================
What is AutoPostback?
Autopostback is the mechanism, by which the page will be posted back to the server
automatically based on some events in the web controls. In some of the web
controls, the property called auto post back.
which if set to true, will send the request to the server when an event happens in
the control.
Whenever we set autopostback attribute to true in any of the controls, the .net
framework will automatically insert few code in to the HTML generated to implement
this functionality.

A Java script method with name __doPostBack (eventtarget, eventargument)


Two Hidden variables with name __EVENTTARGET and __EVENTARGUMENT
OnChange JavaScript event to the control
===================================================================================
==================================
Page Life Cycle With Examples in ASP.Net?
PreInit:-
---------
Check the IsPostBack property to determine whether this is the first time the page
is being processed.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.

Init:-
------
This event fires after each control has been initialized.
Each control's UniqueID is set and any skin settings have been applied.
Use this event to read or initialize control properties.
The "Init" event is fired first for the bottom-most control in the hierarchy, and
then fired up the hierarchy until it is fired for the page itself.

InitComplete:-
--------------
Until now the viewstate values are not yet loaded, hence you can use this event to
make changes to the view state that you want to ensure are persisted after the next
postback.
Raised by the Page object.
Use this event for processing tasks that require all initialization to be complete.

OnPreLoad:-
-----------
Raised after the page loads view state for itself and all controls, and after it
processes postback data that is included with the Request instance.
Before the Page instance raises this event, it loads view state for itself and all
controls, and then processes any postback data included with the Request instance.
Loads ViewState: ViewState data are loaded to controls.
Loads Postback data: Postback data are now handed to the page controls.
Load:-
------
The Page object calls the OnLoad method on the Page object, and then recursively
does the same for each child control until the page and all controls are loaded.
The Load event of individual controls occurs after the Load event of the page.
Use the OnLoad event method to set properties in controls and to establish database
connections.

Control PostBack Event(s):-


---------------------------
ASP.NET now calls any events on the page or its controls that caused the PostBack
to occur.
Use these events to handle specific control events, such as a Button control's
Click event or a TextBox control's TextChanged event.
In a postback request, if the page contains validator controls, check the IsValid
property of the Page and of individual validation controls before performing any
processing.
This is just an example of a control event. Here it is the button click event that
caused the postback.

LoadComplete:-
--------------
Raised at the end of the event-handling stage.
Use this event for tasks that require that all other controls on the page be
loaded.

OnPreRender:-
------------
Raised after the Page object has created all controls that are required in order to
render the page, including child controls of composite controls.
The Page object raises the PreRender event on the Page object, and then recursively
does the same for each child control. The PreRender event of individual controls
occurs after the PreRender event of the page.
The PreRender event of individual controls occurs after the PreRender event of the
page.
Allows final changes to the page or its control.
This event takes place before saving ViewState, so any changes made here are saved.
For example: After this event, you cannot change any property of a button or change
any viewstate value.
Each data bound control whose DataSourceID property is set calls its DataBind
method.
Use the event to make final changes to the contents of the page or its controls.

OnSaveStateComplete:-
---------------------
Raised after view state and control state have been saved for the page and for all
controls.
Before this event occurs, ViewState has been saved for the page and for all
controls.
Any changes to the page or controls at this point will be ignored.
Use this event perform tasks that require the view state to be saved, but that do
not make any changes to controls.

Render Method:-
---------------
This is a method of the page object and its controls (and not an event).
The Render method generates the client-side HTML, Dynamic Hypertext Markup Language
(DHTML), and script that are necessary to properly display a control at the
browser.
UnLoad:-
--------
This event is used for cleanup code.
At this point, all processing has occurred and it is safe to dispose of any
remaining objects, including the Page object.
Cleanup can be performed on:
Instances of classes, in other words objects
Closing opened files
Closing database connections.
This event occurs for each control and then for the page.
During the unload stage, the page and its controls have been rendered, so you
cannot make further changes to the response stream.
If you attempt to call a method such as the Response.Write method then the page
will throw an exception.
===================================================================================
==================================
What is the difference between custom controls and user controls?
Custom controls are basically compiled code, i.e., DLLs. These can be easily added
to toolbox, so it can be easily used across multiple projects using drag and drop
approach. These controls are comparatively hard to create.

But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy
to create but tightly coupled with respect to User Interface and code. In order to
use across multiple projects, we need to copy and paste to the other project as
well.
===================================================================================
==================================
Difference between Response.Redirect and Server.Transfer?
In ASP.Net Technology both "Server" and "Response" are objects of ASP.Net.
Server.Transfer and Response.Redirect both are used to transfer a user from one
page to another.

The following are the different page navigation techniques in asp.net


1. Hyperlink control
2. Response.Redirect
3. Server.Transfer
4. Server.Execute
5. Cross-Page postback
6. Window.Open

The following are the differences between Server.Transfer and Response.Redirect:


--------------------------------------------------------------------------------
1. Just like hyperlink and Response.Redirect, Server.Transfer is used to navigate
to other pages/sites running on the same web server.
2. Server.Transfer cannot be used to navigate to sites/pages on a different web
server.
3. Server.Transfer does not change the URL in the address bar
4. Server.Transfer is faster than Response.Redirect as the redirection happens on
the server in one Request/Response cycle. Response.Redirect() involves 2
Request/Response cycles.
5. With Server.Transfer the Form Variables from the original request are preserved.

===================================================================================
==================================Please Briefly Explain the Usage of Global.asax?
->The Global.asax file, also known as the ASP.NET application file, is an optional
file that contains code for responding to application-level events raised by
ASP.NET or by HttpModules.
->The Global.asax file resides in the root directory of an ASP.NET-based
application. The Global.asax file is parsed and dynamically compiled by ASP.NET.
->The Global.asax file itself is configured so that any direct URL request for it
is automatically rejected; external users cannot download or view the code written
within it.
->The Global.asax file does not need recompilation if no changes have been made to
it. There can be only one Global.asax file per application and it should be located
in the application's root directory only.

The Global.asax contains the events that are listed (and created by default, at
least in Visual Studio 2008):
Application_Start
Application_End
Session_Start
Session_End
Application_BeginRequest
Application_AuthenticateRequest
Application_Error
===================================================================================
==================================
What are the different types of Validation controls in ASP.NET?
In order to validate user input, ASP.NET provides validation server controls. All
validation controls inherit from BaseValidator class which contains the common
validation properties and methods like ControlToValidate, Enabled, IsValid,
EnableClientScript, ValidationGroup,Validate(), etc.

ASP.NET provides a range of validation controls:


------------------------------------------------
RequiredFieldValidator validates compulsory/required input.
RangeValidator validates the range. Validates that input falls between the given
range values.
CompareValidator validates or compares the input of a control with another control
value or with a fixed value.
RegularExpressionValidator validates input value against a defined regular
expression pattern.
CustomValidator allows to customize the validation logic with respect to our
application logic.
ValidationSummary displays all errors on page collectively.
===================================================================================
==================================
What are the types of Authentication in ASP.NET?
There are three types of authentication available in ASP.NET:
->Windows Authentication: This authentication method uses built-in windows security
features to authenticate user.
->Forms Authentication: authenticate against a customized list of users or users in
a database.
->Passport Authentication: validates against Microsoft Passport service which is
basically a centralized authentication service.
===================================================================================
==================================
Explain ASP.NET State Management Techniques?
What is the need of State Management:-
--------------------------------------
State basically means an interaction between the user and the server and the HTTP
Protocol acts like a bridge between them.
But since the HTTP Protocol is a Stateless protocol, it is not able to store the
state during that session. With each request the objects are created and memory is
being allocated. These resources are destroyed once the server completes its
process.
So the cycle of "Creation Of Objects and Utilization of Server Memory" ----
"Processing Of the Request" ---- "Destruction of the Created Resources" continues
for each and every user's request.
In such a case, the information given by the user or the State of an Application
gets lost during each round trip. So this is where State Management helps.

State Management can be defined as the technique or the way by which we can
maintain / store the state of the page or application until the User's Session
ends.

State Management Techniques


---------------------------
ASP.NET provides us with 2 ways to manage the state of an application. It is
basically divided into the 2 categories:
-> Client Side State Management.
-> Server Side State Management.

Client Side State Management:


-----------------------------
It is a way to store the user's specific information or the state of the
application on the client's machine or in the page itself. The server resources
(e.g. server's memory) is not at all utilized during the process.
This management technique basically makes use of the following:
->View State
->Hidden Fields
->Query String
->Cookies
->Control Fields

View State:-
------------
View state is the method that can be used to preserve page and control values
between round trips. When the HTML markup for the page is rendered, the current
state of the page and values that must be retained during postback are serialized
into base64-encoded strings. This information is then put into the view state
hidden field.

It basically makes use of a "Dictionary Object" to store data, which means that the
information is stored in a key and value pair. It stores this information in a
Hidden field on the page itself in a hashed format. A View State can store a string
value only of a specific length. If the length is exceeded then the excess
information is stored in another hidden field.

View State Settings


-------------------
View State is customizable. With the term "Customizable" I mean, that we can apply
settings to a View State to store a value at various levels. We can set the View
State at various levels like:

->Setting View State at Application Level - If we do not want our pages in the
Application to use view state, then we can disable or enable it in the web.config
file, as shown in the image below.
->Setting View State at Page Level - If we do not want a specific page to use View
State, then we can disable or enable it in the @ Page Directive which is the first
line of our aspx page.
->Setting View State at Control Level - If we do not want a specific control to use
View State, then we can disable or enable it at a Control levels.

Advantages of using a View State


--------------------------------
-> It is very simple to use.
-> It is customizable, as shown above.
-> View State store the value in the page itself, hence do not use server
resources.

Disadvantages of using a View State


-----------------------------------
-> By default Information is not encrypted, so it can be easy for a Hacker to get
its value.
-> Cannot be used to store sensitive data (eg: Passwords, Credit Card Pins, etc).
-> Might make a page heavy if lots of data is stored in View State.

Hidden Fields:-
---------------
ASP.NET provides a server control called "Hidden Field" which can be used to store
a value at a page level, which is similar to a View State. The value of the Hidden
Field is sent along in the HTTP Form Collection along with the value of other
controls.

Advantages
-----------
-> Very simple to use.
-> Hidden Fields store the value in the page itself, hence do not use server
resources.

Disadvantages
-------------
-> Will make a page heavy, if too many Hidden Fields are used to store data.
-> Cannot store sensitive data, as the value that is stored is neither hashed, nor
encrypted.

Query String:-
--------------
A Query String is a string which is appended to the end of the Page URL. It is very
simple to use and can be used to send data across pages. It stores information in a
key - value pair. A "?" signature is used to append the key and value to the page
URL.

Advantages:
-----------
-> Easy to use.
-> No extra effort is needed to code.
-> No server resources are required
-> All browser supports QueryString
-> Query String is contained in the HTTP request for a specific URL.

Disadvantages:
--------------
-> There is a limit to URL length of 255 characters.
-> Query String data is directly visible to user thus leading to security problems

Cookies:-
---------
ASP.Net provides another way of state management, that is Cookies. Cookies are one
of the best ways of storing information. It is nothing but a text file which is
stored on the client's machine.

When the user sends a request to the server, the server creates a cookie and
attaches a header and sends it back to the user along with the response. The
browser accepts the cookie and stores it at a specific location on the client's
machine. Even large sites like Gmail, Facebook, Yahoo use cookies.
There are 2 ways of assigning / storing values in cookies.

->Using the Request Object:-


this.Request.Cookies["UserName"].Value=txtUserName.Text.Trim();

->Using the HTTPCookies Object:-

Advantages
-----------
Very easy to use.
Stored on the client's machine, hence no server resources are utilized.

Disadvantages
-------------
A user can disable cookies using browser settings.
Since the cookies are stored on the client's machine, there are chances that if the
client's machine is hacked then the hacker can view these cookie values. Hence we
should not store sensitive information in cookies.

Server Side State Management:-


-------------------------------
It is another way which ASP.NET provides to store the user's specific information
or the state of the application on the server machine. It completely makes use of
server resources (the server's memory) to store information.

This management technique basically makes use of the following:


->Application State
->Session State
->Profile Properties

Application State:
------------------
Application state is stored in memory on the server and is faster than storing and
retrieving information in a database. Application state applies to all users and
sessions. Therefore, application state is a useful place to store small amounts of
often-used data that does not change from one user to another user.
(OR)
->If the information that we want to be accessed or stored globally throughout the
application, even if multiple users access the site or application at the same
time, then we can use an Application Object for such purposes.
->It stores information as a Dictionary Collection in key - value pairs. This value
is accessible across the pages of the application / website.
->There are 3 events of the Application which are as follows
Application_Start
Application_Error
Application_End

Advantages of application state:


--------------------------------
Application object memory relased when we removed.
Multi user can able to access application variable.
To avoid deadlock or conflict we should use Lock and Unlock when we use write or
update in the application object.
Other application can't access this application values.

Disadvantages of application state:


-----------------------------------
-Application variable will exists until exit our application.
-If we do not have Lock() and Unlock, deadlock will occur.
-Its gloable variable so anyone can access within this application.
-It is lost whenever the application is stopped or restarted because application
state is stored in server memory, For example, if the Web.config file is changed,
the application is restarted and all application state is lost unless application
state values have been written to a non-volatile storage medium such as a database.

Session State:-
---------------
Session is one of the most common way which is being used by developers to maintain
the state of the application. The Session basically stores the values as a
dictionary collection in key/value pairs. It completely utilizes server resources
to store the data. It is a secure way of storing data, since the data will never be
passed to the client.

For each and every user, a separate Session is created, and each and every Session
has its Unique ID. This ID is being stored in the client's machine using cookies.
If there are multiple users who are accessing a web application, then for each user
a separate Session is created. If a single user logs in and logs out the Session is
killed, then if the same user again logs into the application, then a new Session
ID is being created for the same user.

Cookieless SessionIDs:
----------------------
By default, the SessionID value is stored in a non-expiring session cookie in the
browser. However, you can specify that session identifiers should not be stored in
a cookie by setting the cookieless attribute to true in the sessionState section of
the Web.config file.

The following example shows a Web.config file that configures an ASP.NET


application to use cookieless session identifiers.
<configuration>
<system.web>
<sessionState cookieless="true"
regenerateExpiredSessionId="true" />
</system.web>
</configuration>

ASP.NET maintains cookieless session state by automatically inserting a unique


session ID into the page's URL. For example, the following URL has been modified by
ASP.NET to include the unique session ID lit3py55t21z5v55vlm25s55:
http://www.example.com/(S(lit3py55t21z5v55vlm25s55))/orderform.aspx

The Session has a default timeout value (by defalut 20 minutes). We can also set
the timeout value for a session in the web.config file.

There are various ways in which we can store a session and they are as follows:
->OFF
->InProc
->State Server
->SQL Server

OFF - If we do not want to use sessions in our application, then we can set the
mode as "OFF".

InProc - This is the default mode which is used in ASP.NET to store session
variables. InProc mode basically stores the session value in the process in which
the ASP.NET application is running. Since it is stored in the same process, it
provides high performance as compared to other modes.

State Server - If we use this mode, then a separate Windows Service which runs in a
different process stores the Session. It basically isolates the Session from the
ASP.NET running process. It provides less performance as compared to the Inproc
mode.

SQL Server - This mode stores the Session in SQL Server instead of the server's
memory. If our application is stored on multiple server machines, then it becomes
difficult to use the "Inproc" mode since the request can go to any server for
processing. So if we want to use sessions in such cases, then we can store the
Session in SQL Server so that it becomes centralized and can be accessed by any
server during the request process. It is the most secure way of storing Sessions
but gives the lowest performance for an application.

If the Global.asax file or Web.config file for an ASP.NET application is modified,


the application will be restarted and any values stored in application state or
session state will be lost. Be aware that some anti-virus software can update the
last-modified date and time of the Global.asax or Web.config file for an
application.

<sessionState mode="SQLServer"
cookieless="true "
regenerateExpiredSessionId="true "
timeout="30"
sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;"
stateNetworkTimeout="30"/>

ASP.NET Session State advantages


--------------------------------
- Sessions are very simple to use. If you have a global variable related to
individual visitor, you can place it in session and it will be visible from all
pages on website.
- If InProc mode is used, any type of object could be stored. In case that Session
State or SQL Server is used, objects must be serialized before saving.
- Separated global data for each visitor. Every visitor has its own collection of
session variables.

ASP.NET Session State disadvantages


-----------------------------------
- Every variable is stored as Object. That means you need to convert Object to
certain type when read session variable.
- In addition to this, if session is empty, Object will be null. Before reading
session variable, you need to check it for null. Even if variable is initialized
before, it could be null because session is expired. An attempt to use null session
value could return an exception. If value of session variable is null, common
practice is to use some default value instead of meaningless null. If value is not
null, you must convert it to appropriate type because all session variables are
type of object. When do all this things, you should pay attention to avoid hard
coding. More about reading and writing of session variables on scalable and
maintainable way you can read in How To Write, Read and Delete Session State
Variables tutorial.
- Variable name is type of string. If you hard code name of the variable, there is
an option to make type mistake somewhere. The problem is, if you try to read
session variable that doesn't exist, ASP.NET will not return any exception or
warning. It will simply create new variable with wrong name which has null value.
These types of errors could be hard to find.
- Session data should not be used for storing of sensitive data. There is a
possibility that malicious user obtain regular visitor's session id. If session
state is used to store information like: "allow access to administration area or
not" or something like that, attacker could see website's sensitive data, other's
private data, edit database, delete content etc.
- If InProc mode is used, sessions easily exhaust all server resources and thus
decrease website performances.
===================================================================================
==================================
What happens when the user sends a request to the server and what the server does
to process that request?
It is very important to know what happens when the user sends a request to the
server and what the server does to process that request.

Fact 1 - This is just a brief description of the ASP.NET environment creation:


------------------------------------------------------------------------------
Whenever the user sends a request to the server, the server first locates the page
and checks who will process the request.
Then it creates an App Domain which is a space in the memory / Memory Unit which
creates a Hosting Environment.
It then creates 4 different Objects like:
Http Response Object
Http Request Object
Http Context Object
Http Application Object
These objects are process the request and sends a response to the user in HTML
format.
Note - The App Domain is created only once for each Website or an application. The
Http Application Object is also created only once. The creation happens when the
user requests a website for the first time.
===================================================================================
==================================
What is the need of State Management?
In today's world everything is becoming Internet / Web based. Whatever work it may
be, whether related to Banking, Education, Entertainment or Shopping we can do it
over the internet very easily. If we try to compare today's generation with the
previous generation then I would simply say that we cannot live without the
Internet.

As food, clothing and shelter are our basic needs, the Internet has also become a
part of our basic necessities. If we think about our future, then I would say
"Cloud Computing", which is already well developed and is currently still evolving,
will take this Internet World to a higher level.

Let us assume that someone is trying to access a banking website and he has to fill
in a form.
So the person fills in the form and submits it. After submission of the form, the
person realizes he has made a mistake. So he goes back to the form page and he sees
that the information he submitted is lost. So he again fills in the entire form and
submits it again. This is quite annoying for any user. So to avoid such problems
"STATE MANAGEMENT" acts as a savior for developers like us.

State basically means an interaction between the user and the server and the HTTP
Protocol acts like a bridge between them.
But since the HTTP Protocol is a Stateless protocol, it is not able to store the
state during that session. With each request the objects are created and memory is
being allocated. These resources are destroyed once the server completes its
process.
So the cycle of "Creation Of Objects and Utilization of Server Memory" ----
"Processing Of the Request" ---- "Destruction of the Created Resources" continues
for each and every user's request.
In such a case, the information given by the user or the State of an Application
gets lost during each round trip. So this is where State Management helps.
===================================================================================
==================================
What is HTTP Protocol?
Hyper Text Transfer Protocol is the base or I would rather say, is the core part or
the foundation of our World Wide Web. It basically makes use of the TCP Protocol
for communicating with the server. A specific port is being used by this protocol
while communicating with the server.

HTTP provides various methods which represent the actions it will perform while
communicating with the server. Some of its methods are "GET", "POST", "DELETE",
"HEAD", etc....

If a user tries to access a website, say (http://www.asp.net/) and let us assume


that the requested page is an ASPX page. So what happens is, the HTTP Protocol
takes the request being sent by the client (using his browser) and sends it to the
server. The server then locates the requested page and tells the ASP.NET engine to
process the request.

The ASP.NET Engine processes the request and sends a response back to the client in
an HTML format. Once again the HTTP protocol is relevant; the HTTP protocol takes
the response and sends it to the client, thus the response is shown in the client's
browser.

So the HTTP Protocol, which is also called a "Request - Response" Protocol, acts
like a bridge between the client and the server.
===================================================================================
==================================
What is Caching and what are the types of Caching in ASP.NET?
Caching improves the performance and scalability of an application.
Caching is the technique of storing frequently used data/pages in memory.

Caching a page:-
----------------
In order to cache a page's output, we need to specify an @OutputCache directive at
the top of the page. The syntax is as shown below:
<%@ OutputCache Duration=5 VaryByParam="None" %>

As you can see, there are two attributes to this directive. They are:
Duration - The time in seconds of how long the output should be cached. After the
specified duration has elapsed, the cached output will be removed and page content
generated for the next request. That output will again be cached for 5 seconds and
the process repeats.

VaryByParam - This attribute is compulsory and specifies the querystring parameters


to vary the cache.
In the above snippet, we have specified the VaryByParam attribute as None which
means the page content to be served is the same regardless of the parameters passed
through the querystring

<%@ OutputCache Duration=5 VaryByParam="id" VaryByCustom="browser" %>


This will vary the cached output not only for the browser but also its major
version. I.e., IE5, IE 6, Netscape 4, Netscape 6 will all get different cached
versions of the output.

Caching page fragments:-


------------------------
Sometimes we might want to cache just portions of a page. For example, we might
have a header for our page which will have the same content for all users. There
might be some text/image in the header which might change everyday. In that case,
we will want to cache this header for a duration of a day.

The solution is to put the header contents into a user control and then specify
that the user control content should be cached. This technique is called fragment
caching.
To specify that a user control should be cached, we use the @OutputCache directive
just like we used it for the page.

<%@ OutputCache Duration=10 VaryByParam="None" %>


With the above directive, the user control content will be cached for the time
specified by the Duration attribute [10 secs]. Regardless of the querystring
parameters and browser type and/or version, the same cached output is served.

Data Caching:-
--------------
ASP.NET also supports caching of data as objects. We can store objects in memory
and use them across various pages in our application. This feature is implemented
using the Cache class. This cache has a lifetime equivalent to that of the
application. Objects can be stored as name value pairs in the cache. A string value
can be inserted into the cache as follows:

Cache["name"]="Smitha";
The stored string value can be retrieved like this:

if (Cache["name"] != null)
Label1.Text= Cache["name"].ToString();

To insert objects into the cache, the Add method or different versions of the
Insert method of the Cache class can be used. These methods allow us to use the
more powerful features provided by the Cache class. One of the overloads of the
Insert method is used as follows:

Cache.Insert("Name", strName, new CacheDependency(Server.MapPath("name.txt"),


DateTime.Now.AddMinues(2),TimeSpan.Zero);
The first two parameters are the key and the object to be inserted. The third
parameter is of type CacheDependency and helps us set a dependency of this value to
the file named name.txt. So whenever this file changes, the value in the cache is
removed. We can specify null to indicate no dependency. The fourth parameter
specifies the time at which the value should be removed from cache. [See example 5
for an illustration.] The last parameter is the sliding expiration parameter which
shows the time interval after which the item is to be removed from the cache after
its last accessed time.

The cache automatically removes the least used items from memory, when system
memory becomes low. This process is called scavenging. We can specify priority
values for items we add to the cache so that some items are given more priority
than others:

Cache.Insert("Name", strName,
new CacheDependency(Server.MapPath("name.txt"),
DateTime.Now.AddMinutes(2), TimeSpan.Zero,
CacheItemPriority.High, null);
The CacheItemPriority enumeration has members to set various priority values. The
CacheItemPriority.High assigns a priority level to an item so that the item is
least likely to be deleted from the cache.

Caching Location:-
------------------
In which location caching can be done so ASP.NET has the following 4 caching
locations where we can do the cache:

->Client Caching: The cache data is stored inside the client's browser on the local
disk as a temporary file or in the browser's internal memory. So it reduces the
network traffic and the client can be accessed easily but it is totally browser
dependent so it is not shareable.
->Proxy Caching: It stores the caching information between the client and the web
server in a shared location so that all clients can use the same shared data.
->Reverse Proxy Caching: The web server has a Proxy Server in the front so that it
reduces the number of requests that they receive. This allows the Proxy Server to
respond to frequently received requests and only passes other requests to the web
server. This is called a reverse proxy and it reduces the number of requests and
can easily be accessed but it increases the network traffic because the Proxy
Server is the front of the web server.
->Web Server Caching: The cache data is stored inside the web server.

Advantages:-
------------
Reduce load on Web Services/ Database
Increase Performance
Reliability (Assuming db backed cache. Server goes down and db is backed by cache
there is no time wasted to repopulate an in memory cache)

Disadvantages:-
---------------
Could run into issues syncing caches
Increased Maintenance
Scalability Issues
===================================================================================
==================================
How to make ViewState secure in ASP.NET?
The ASP.NET ViewState is a client side state management mechanism. The ViewState is
stored in a hidden field with an ID __VIEWSTATE.
The ViewState information is stored as a Base64 encoded string, and is not an
encrypted string. So it can be easily decoded.
The main reasons for using Base64 encoding are as follows:
----------------------------------------------------------
->Base64 makes a string suitable for HTTP transfers
->It makes it a little harder to read
But people often get confused that this is an encrypted string.

There are two different ways in which you can prevent someone from decrypting
ViewState data.
-----------------------------------------------------------------------------------
----------
->You can make sure that the ViewState information is tamper-proof by using "hash
codes". You can do this by adding EnableViewStateMAC=true in your page directive.
MAC stands for "Message Authentication Code".
When we use EnableViewStateMac="True", during ViewState save, ASP.NET internally
uses a hash code. This hash code is a cryptographically strong checksum. This is
added with the ViewState content and stored in a hidden filed. During postback, the
checksum data is verified again by ASP.NET. If there is a mismatch, the postback
will be rejected.

->The second option is to set ViewStateEncryptionMode="Always" with your page


directives. This will encrypt the ViewState data.
ViewStateEncryptionMode has three different options that can be set:
- Always: encrypt the View State always.
- Auto: encrypt if a control requests for encryption. For this to happen, the
control must call the Page.RegisterRequiresViewStateEncryption() method.
- Never: Never encrypt the ViewState.

Try to avoid ViewState encryption if it is not necessary as it can cause


performance issues.
===================================================================================
==================================
Difference between SessionState and ViewState in ASP.NET?
ViewState:-
------------
-> The view state is maintain in page level
-> Scope of a view state is specific to a page only
-> The ViewState is used to store data that can be used during postbacks for page
level
-> The view state is a client side state management technique to store data
-> The ViewState of one page is not visible in another page which means when user
requests another page, the previous page stored data will be no longer available to
use
-> The ViewState has no specific expiration date or time to wipeout stored data

SessionState:-
--------------
-> The session state is maintain in session level/per user.
-> Scope of a session state is for a user session
-> The SessionState is used to store data that can be used anywhere within website
or web application in asp.net
-> The session state is a server side state management technique to store data
-> The SessionState value is available in all pages within a user session which
means the data will no longer available if user close the browser or session
timeout occurs (usually 20min which is default for session)
-> The SessionState will clear session when the current user close his web browser
or session dies due to inactivity of the user within set timeout (default is 20min)
===================================================================================
==================================
Difference between Web.config Vs App.config Vs Machine.config?
Web.config :-
------------
It is a configuration file, which is used in web application and it can be an
ASP.NET project or MVC project. Some project contains multiple web.config file
inside the same project but with different folder. They have their unique benefits.
You can create several web.config file in each folder with their unique benefits as
per your project requirement.

It is used to store the application level configuration. Sometimes it inherits the


setting from the machine.config. It parses at runtime, means if you make any
changes then web application will load all the settings in the config file. You
don�t need to create a web.config file because it is auto generated when you create
a new web application. If you want to create a web.config manually you can create
it.

Sample Example:-
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
</system.web>
</configuration>
App.config:-
------------
It is also a special type of configuration file which is basically used with
Windows Services, Windows application, Console Apps or it can be WPF application or
any others.

It parses at compile time; it means if you edit the app.config when program is
running, then you need to restart the application to reload the configuration
setting into the program.

When you run the application which contains the app.config, at the time of
compilation a copy of app.config with different name moves into build folder for
running the application, So that's why we need to restart the program if any
changes made in app.config.

It is not added auto when you create a project, to add this you need to go to
solution explorer and choose Add New Item and choose �Application Configuration
File�. Windows application always contains the App.config file into the project.

Sample Example:-
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="MyKey"
connectionString="Data Source=localhost;Initial Catalog=ABC;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>

Machine.config:-
----------------
It is a special type of configuration file which creates into the OS when you
install visual studio. This stores machine level configuration setting. Only one
machine.config file exists into the system and it stores highest level of
configuration settings.

Machine.config settings apply to all web applications which is residing on the


server. The setting of machine.config can be overridden by web.config�s settings.
If your system does not contain the machine.config then you cannot execute the
application.

Path of Machine.config:-
32-bit System--%windir%\Microsoft.NET\Framework\[version]\config\machine.config
64-bit System--%windir%\Microsoft.NET\Framework64\[version]\config\machine.config

Sample Example:-
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Please refer to machine.config.comments for a description and
the default values of each configuration section.

For a full documentation of the schema please refer to


http://go.microsoft.com/fwlink/?LinkId=42127

To improve performance, machine.config should contain only those


settings that differ from their defaults.
-->
<configuration>
<configSections>
</configSections>
</configuration>
===================================================================================
================================== What is CrossPagePostBack in ASP.NET?
The CrossPagePostBack is used to access previous page controls to next page using
PostBackUrl property of web server control in Asp.net.
===================================================================================
==================================
Which method do you use to kill explicitly a users session?
The Session.Abandon() method kills the user session explicitly. You can also use
Session.Remove(�mySession�) method to remove any specific one session OR
Session.RemoveAll() method to remove all the sessions.
===================================================================================
==================================
How many types of Cookies are available in ASP.NET?
Basically Cookies are one of the following 2 types:
Persistent Cookies: Persistent Cookies are Permanent Cookies stored as a text file
in the hard disk of the computer.

Non-Persistent Cookies: Non-Persistent cookies are temporary. They are also called
in-memory cookies and session-based cookies. These cookies are active as long as
the browser remains active, in other words if the browser is closed then the
cookies automatically expire.
===================================================================================
==================================
What is the difference between ASP.NET Label and Literal Control?
1. In many ways a Literal control is similar to a Label control. Both of these
controls are used to display Text on a webform. The Text property can be set in the
HTML or in the code-behind.

2. Label control wraps the text in a span tag when rendered. Any style that is
applied to the Label control, will be rendered using the style property of the span
tag.

For example, the following HTML


<asp:Label ID="Label1" runat="server" Text="Lable Text"
ForeColor="Red" Font-Bold="true" ></asp:Label>

Will be rendered as
<span id="Label1" style="color:Red;font-weight:bold;">Lable Text</span>

3. A literal control, doesn't output any surrounding tags. The Text is displayed as
is.
For example, the following HTML
<asp:Literal ID="Literal1" runat="server"
Text="Literal Control Text"></asp:Literal>

will be rendered as
Literal Control Text

4. If you want to apply any styles to a literal control, include them in the Text
of the literal control. For example, the following HTML sets the font to red color
and bold.
<asp:Literal ID="Literal1" runat="server"
Text="<b><font color='Red'>Literal Control Text</font></b>">
</asp:Literal>

The above HTML will be rendered as


<b><font color='Red'>Literal Control Text</font></b>

5. So, if you just want the text to be displayed without any styles, then use
Literal control, else use Label control.

6. By default, both the Label and Literal Control's does not encode the text they
display. For example, the following HTML displays a javascript alert
<asp:Label ID="Label" runat="server"
Text="<script>alert('Lable Text');</script>">
</asp:Label>
<br />
<asp:Literal ID="Literal1" runat="server"
Text="<script>alert('Literal Text');</script>">
</asp:Literal>

and will be rendered as


<span id="Label"><script>alert('Lable Text');</script></span>
<br />
<script>alert('Literal Text');</script>

7. To HTML encode the Label Text, Server.HtmlEncode() method can be used, and for
Literal control, Mode property can be used.
<asp:Label ID="Label1" runat="server">
<%=Server.HtmlEncode("<script>alert('Lable Text');</script>")%>
</asp:Label>
<br />
<asp:Literal ID="Literal1" runat="server"
Text="<script>alert('Literal Text');</script>"
Mode="Encode"></asp:Literal>

The above HTML will be rendered as


<span id="Label1">&lt;script&gt;alert(&#39;Lable Text&#39;);&lt;/script&gt;</span>
<br />
&lt;script&gt;alert(&#39;Literal Text&#39;);&lt;/script&gt;

8. Literal control is a light weight control, when compared with the Label control.

9. The inheritance hierarchy for Literal control class is (Object => Control =>
Literal), where as for the Lable control, the hierarchy is (Object => Control =>
WebControl=> Label)
===================================================================================
==================================
What is the difference between Web Server and HTML Controls?
The Web Server controls are server-side controls so all the validations are
performed at the server-side; whereas the HTML controls are client-side controls so
all the validations are performed at the client-side. Web browser does not
understand server controls so after page processing all the server controls are
converted into html controls to display results on the browser.
===================================================================================
==================================
What is the appSettings section in Web.config file?
Usually the Web.config file contains configuration settings for a web application.
The appSettings section contains set of user-defined values for the whole web
application. Following is the simple example that specifies the �ConnectionString�
and �Email� that we can use later throughout the project.

<configuration>
<appSettings>
<add key="ConnectionString" value="myConnectionString here.." />
<add key="Email" value="myemail@domain.dom"/>
</appSettings>
</configuration>
===================================================================================
==================================
Why do we need nested Master Pages in an ASP.NET Website?
It is appropriate to use nested Master Pages in an ASP.NET Website when we deal
with several hierarchical levels in a Website. For an example, if we are creating
��School Management System�� so there should be several hierarchies of departments
such as Student, Teacher, and Admin etc; In this case we can use nested master
pages.
===================================================================================
==================================
What are the major built-in objects in ASP.NET?
Following are all the common built-in objects in ASP.NET that we can use frequently
during website development.
Request
Response
Data
Application
Server
Context
Session etc
===================================================================================
==================================
What is the difference between GridView and DataGrid?
The GridView is a web control; whereas the DataGrid is a windows control.
GridView:
� In GridView control, you can add paging, sorting, or editing capabilities with
enabling simple gridview�s property
� GridView has �EditTemplates� template to enable inline editing
DataGrid:
� In DataGrid control, we need to add events for paging, sorting, or editing
capabilities
� DataGrid does not have �EditTemplates� template to enable inline editing
===================================================================================
==================================
What are Custom User Controls? How can you register it to a webpage?
The Custom User Controls are the controls that are defined by developers. These
controls are a mixture of custom behavior and predefined behavior. These controls
works similar to other web server controls.

The @Register directive is used to register a custom server control to a webpage.

//Register control using following statement right after @ Page directive


<%@ Register TagPrefix="myASP" TagName="myControl" Namespace="MyApp.Controls"
Assembly="MyApp" %>
//You can use like this in your .aspx page..
<myASP:myControl runat="server"/>
===================================================================================
==================================
What is the difference between Authentication and Authorization?
The Authentication is the process of validating the identity of a user; whereas
Authorization is the process of granting access privileges to resources or tasks
within an application.
===================================================================================
==================================
What is IIS? What is the use of IIS?
The IIS stands for Internet Information Services which is created by Microsoft to
provide Internet based services to your ASP.NET web applications. It is use to host
your web applications on the server. It makes your local computer to work as a web
server which provides functionality to deploy one or more web applications on the
server.
(OR)
In simple terms, a web server, is a software, that is used to deliver web pages to
clients using the Hypertext Transfer Protocol (HTTP). For example, IIS is a web
server that can be used to run asp.net web applications.
===================================================================================
==================================
What is the use of App_Code folder in Asp.net website?
When you create website from Visual Studio, the App_Code folder will automatically
created in the website root directory, otherwise you need to add it by right
clicking on the project. We can use it to store the files that we want to use in
our website, like common classes, text files, pdf files, email templates, reports
etc.
===================================================================================
==================================
Difference between ViewState and Session and Application in ASP.NET?
ViewState:-
-----------
1. ViewState of a webform is available only with in that webform
2. ViewState is stored on the page in a hidden field called _ViewState. Because of
this, the ViewState, will be lost, if you navigate awaya from the page, or if the
broswer is closed.
3. ViewState is used by all asp.net controls to retain their state across postback

Session State:-
---------------
1. Session state variables are available across all pages, but only for a given
single session. Session variables are like single-user global data.
2. Session state variables are stored on the web server.
3. SessionState variables are cleared, when the user session times out. The default
is 20 minutes. This is configurable in web.config

Application State:-
-------------------
1. Application State variables are available across all pages and across all
sessions. Application State variables are like multi-user global data.
2. Application State variables are stored on the web server.
3. Application State variables are cleared, when the process hosting the
application is restarted.
===================================================================================
==================================
Q) Difference between Machine.Config and Web.Config?
Machine.Config:-
----------------
-> This is automatically installed when you install Visual Studio. Net.
-> This is also called machine level configuration file.
-> Only one machine.config file exists on a server.
-> This file is at the highest level in the configuration hierarchy.

Web.Config:-
------------
-> This is automatically created when you create an ASP.Net web application
project.
-> This is also called application level configuration file.
-> We can create more than one web.config file based on requirement.
-> This file inherits setting from the machine.config
===================================================================================
==================================
Q) Differentiate between web.config, app.config and machine.config files?
web.config file:-
-----------------
-> web.config is used for ASP.NET Web Projects / Web Services. web.config by
default has several configurations required for the web application. It is also
called Application Level Configuration File and inherits setting from the
machine.config file.
-> web.config is parsed at runtime, so if you edit the web.config file, the web
application will automatically load the changes in the config file.
-> web.config file is automatically generated when new web application created.
-> You can have more than one web.config file in your application. Specifically,
you can have a web.config for each folder under your web application.
-> The web.config file is required for ASP.NET webpages.

app.config file:-
-----------------
-> app.config is used for Windows Forms, Windows Services, Console Apps and WPF
applications.
-> app.config is parsed at compile time, so if you edit the app.config file, you
have to restart the application. At compile time a copy of the app.config file is
taken, renamed to [output].config and moved to the build folder. This copy can then
be modified, and your modifications will be read each time the application/service
is started.
-> app.config is not added automatically to an application. You can go to the
solution explorer, select 'Add new item' and add the 'Application Configuration
File'.
-> There is always one app.config file in a window application.
-> The app.config file is optional in an application and doesn't have to be used
when writing desktop applications.

machine.config file:-
---------------------
-> machine.config file is automatically created on your system when you install
Visual Studio.Net. This is also called Machine Level Configuration File. Only one
machine.config file exists on a server, and is at the highest level in the
configuration hierarchy.
-> The settings of machine.config file are applied to all the web applications
residing on the server.
-> The machine.config file is overridden by the web.config file.
-> Without the machine.config file, application can not be executed.
===================================================================================
==================================
Q) Difference between session and cookies in asp.net?
Cookies:-
---------
1.Cookies can store only "string" datatype
2.They are stored at Client side
3.Cookie is non-secure since stored in text format at client side
4.Cookies may or may not be individual for every client
5.Due to cookies network traffic will increase.Size of cookie is limited to 40 and
number of cookies to be used
is restricted to 20.
6.Only in few situations we can use cookies because of no security
7.We can disable cookies
8.Since the value is string there is no security
9.We have persistent and non-persistent cookies
Session:-
---------
1.Session can store any type of data because the value is of datatype of "object"
2.These are stored at Server side
3.Session are secure because it is stored in binary format/encrypted form and it
gets decrypted at server
4.Session is independent for every client i.e individual for every client
5.There is no limitation on size or number of sessions to be used in an application

6.For all conditions/situations we can use sessions


7.we cannot disable the sessions.Sessions can be used without cookies also(by
disabling cookies)
8.The disadvantage of session is that it is a burden/overhead on server
9.Sessions are called as Non-Persistent cookies because its life time can be set
manually
===================================================COMPLETED=======================
==================================

===================================================================================
==================================
ASP.NET MVC:
============

Q) WHAT IS MVC (Model View Controller)?


=>Asp.Net MVC is a new Framework built on the top of Microsoft .Net Framework to
develop web application.
=>ASP.NET MVC framework implements the MVC pattern which helps to provides
separation of code and also provide better support for test-driven development
(TDD).
=>The Model-View-Controller (MVC) pattern was introduced in 1970s. It is a software
design pattern that splits an application into three main aspects : Model, View and
Controller. Moreover, MVC pattern forces a separation of concerns within an
application for example, separating data access logic and business logic from the
UI.
=>Asp.Net MVC is a lightweight and highly testable open source framework for
building highly scalable and well designed web applications. It is handled by three
objects Model-View-Controller.

Model�
-------
The Model can be broken down into several different layers as given below:
--------------------------------------------------------------------------
Objects or ViewModel Layer:
This layer contains simple objects or complex objects which are used to specify
strongly-typed view. These objects are used to pass data from controller to
strongly-typed view and vice versa. The classes for these objects can have specific
validation rules which are defined by using data annotations. Typically, these
classes have those properties which you want to display on corresponding view/page.

Data Access Layer:


This layer provides objects to access and manipulate the database of your
application. Typically, this layer is made by using ORM tools like Entity Framework
or NHibernate etc.
Business Layer:
This layer helps you to implement your business logic and validations for your
application. This layer make use of Data Access Layer for persisting data into
database. Also, this layer is directly invoked by the Controller to do processing
on input data and sent back to view.

View�
------
The View is responsible for transforming a model or models into UI. The Model is
responsible for providing all the required business logic and validation to the
view. The view is only responsible for displaying the data, that is received from
the controller as the result.

Moreover, views in Asp.Net MVC, handles the UI presentation of data as the result
of a request received by a controller. By default, views are stored in the Views
folder of the project.

Controller�
-----------
The Controller is responsible for controlling the application logic and acts as the
coordinator between the View and the Model. The Controller receive input from users
via the View, then process the user's data with the help of Model and passing the
results back to the View.

Moreover, controllers in Asp.Net MVC, respond to HTTP requests and determine the
action to take based upon the content of the incoming request. By default,
controllers are stored in the Controllers folder of the project.
===================================================================================
==================================
Q) How do I use constraints in ASP.net MVC 4 RouteConfig.cs (OR) ASP.NET MVC: Route
with optional parameter, but if supplied, must match numbers only?

1st way:-
---------
routes.MapRoute(
name: "Videos",
url: "{controller}/{action}/{id}",
defaults: new { controller = "VideoList", action = "Index", id="" },
constraints: new { id = @"\d+"}
);

2nd way:-
---------
routes.MapRoute("ProfileDetails", "profile/{userId}",
new {controller = "Profile",
action = "Details",
userId = UrlParameter.Optional},
new {userId = @"\d+"});
===================================================================================
==================================
2.EXPLAIN ASP.NET MVC FILTERS AND ATTRIBUTES?
=>In ASP.NET MVC, controllers define action methods that usually have a one-to-one
relationship with possible user interactions, such as clicking a link or submitting
a form. For example, when the user clicks a link, a request is routed to the
designated controller, and the corresponding action method is called.
=>Sometimes you want to perform some logic either before an action method is called
or after an action method runs.
=>To support this, ASP.NET MVC provides filters.
=>Filters are custom classes that provide both a declarative and programmatic means
to add pre-action and post-action behavior to controller action methods.

When to use Filters


-------------------
Typically, Filters are used to perform the following common functionalities in your
ASP.NET MVC application.
-Custom Authentication
-Custom Authorization(User based or Role based)
-Error handling or logging
-User Activity Logging
-Data Caching
-Data Compression

Types of Filters:
-----------------
-Authentication filters (New in ASP.NET MVC5)
-Authorization filters -- To implement authentication and authorization .
-Action filters -- To execute a business logic before and after execution of an
action.
-Result filters -- To execute a business logic before and after execution of a view
result.
-Exception filters -- To handle error raised by controller or action or result of
execution of action

1) Authorization filters:
-------------------------
=>These implement IAuthorizationFilter and make security decisions about whether to
execute an action method, such as performing authentication or validating
properties of the request.
=>The AuthorizeAttribute class and the RequireHttpsAttribute class are examples of
an authorization filter. Authorization filters run before any other filter.

public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter


{
protected virtual bool AuthorizeCore(HttpContextBase httpContext);
protected virtual void HandleUnauthorizedRequest(AuthorizationContext
filterContext);
public virtual void OnAuthorization(AuthorizationContext filterContext);
protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase
httpContext);
}

2) Action Filters:
------------------
=>Action filters are executed before or after an action is executed.
=>The IActionFilter interface is used to create an Action Filter which provides two
methods OnActionExecuting and OnActionExecuted which will be executed before or
after an action is executed respectively.

public interface IActionFilter


{
void OnActionExecuting(ActionExecutingContext filterContext);
void OnActionExecuted(ActionExecutedContext filterContext);
}

Sample Code:-
-------------
public class ValidateUser : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext
filterContext)
{
HttpContext ctx = HttpContext.Current;
if (HttpContext.Current.Session["ID"] == null)
{
filterContext.Result = new RedirectResult("~/Admin/Index");
return;
}
}
}

3) Result Filters:
------------------
=>Result filters are executed before or after generating the result for an action.
=>The Action Result type can be ViewResult, PartialViewResult,
RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and
EmptyResult which derives from the ActionResult class. Result filters are called
after the Action filters.
=>The IResultFilter interface is used to create an Result Filter which provides two
methods OnResultExecuting and OnResultExecuted which will be executed before or
after generating the result for an action respectively.

public interface IResultFilter


{
void OnResultExecuted(ResultExecutedContext filterContext);
void OnResultExecuting(ResultExecutingContext filterContext);
}

4) Exception Filters:
---------------------
=>Exception filters are executed when exception occurs during the actions execution
or filters execution.
=>The IExceptionFilter interface is used to create an Exception Filter which
provides OnException method which will be executed when exception occurs during the
actions execution or filters execution.

public interface IExceptionFilter


{
void OnException(ExceptionContext filterContext);
}

Order of Filter Execution:


--------------------------
All ASP.NET MVC filter are executed in an order. The correct order of execution is
given below:
-Authentication filters
-Authorization filters
-Action filters
-Result filters
-Exception filters
===================================================================================
==================================
Q) WHAT IS MODEL AND VIEWMODEL IN ASP.NET MVC?
Model:
------
A model is an object that we use to send information to the database, to perform
business calculations and to render a view. Usually we put all our model classes in
the Model folder. Model folder is created by default.
ViewModel:
---------
ViewModel is very similar to a "model". The major difference between "Model" and
"ViewModel" is that
we use a ViewModel only in rendering views. We put all our ViewModel classes in a
"ViewModels" named
folder, we create this folder manually. Finally ViewModel is only for Views.

Understand it with an example:


------------------------------
Let's assume we want to implement a view page that will have three textboxes for
Username, Password
and Re-enter Password. To do this we could design a "Model" as given below:

public class Login


{
public String Username { get; set; }
public String Password { get; set; }
public String RePassword { get; set; }
}

For the sake of the view this model works fine. But this is actually an incorrect
approach because we are
trying to overcrowd the database. I can't see any use of the "RePassword" property
in the database.

Now, if we take the advantage of a ViewModel, we can safeguard the database from
redundant data.
Here's how, design the following "Model" that will be our Domain Model:

//this will represent domain of the application


public class Login
{
public String Username { get; set; }
public String Password { get; set; }
}

And then following "ViewModel"


//this will help in rendering great views
public class LoginViewModel
{
public String Username { get; set; }
public String Password { get; set; }
public String RePassword { get; set; }
}
Now, when adding the view, pick the ViewModel class to get the strongly-typed
benefits.

Transforming Model from ViewModel:


----------------------------------
There are various ways to do this. In the form POST action we can create a new
object of type Login
model and then assign the properties one by one and leave the unwanted properties.

[HttpPost]
public ActionResult Login(LoginViewModel viewModel)
{
//validate the ViewModel
//transforming Model (Domain Model) which is Login from ViewModel which is
LoginViewModel
var login = new Login()
{
Username = viewModel.Username,
Password = viewModel.Password
};
//save the login var
return View();
}
===================================================================================
==================================k
Q) How to Pass Multiple Models in Single View in MVC?
In MVC we can pass multiple models from a controller to the single view.

1. Using Dynamic Model:


=======================
Controller Code:
----------------
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to my demo!";
dynamic mymodel = new ExpandoObject();
mymodel.Teachers = GetTeachers();
mymodel.Students = GetStudents();
return View(mymodel);
}
}
View Code:
----------
@using MultipleModelInOneView;
@model dynamic
<p><b>Teacher List</b></p>
@foreach (Teacher teacher in Model.Teachers)
{
}
<p><b>Student List</b></p>
@foreach (Student student in Model.Students)
{
}

2. Using View Model:


====================
public class ViewModel
{
public IEnumerable<Teacher> Teachers { get; set; }
public IEnumerable<Student> Students { get; set; }
}
Controller code:
----------------
public ActionResult IndexViewModel()
{
ViewBag.Message = "Welcome to my demo!";
ViewModel mymodel = new ViewModel();
mymodel.Teachers = GetTeachers();
mymodel.Students = GetStudents();
return View(mymodel);
}
View code:
----------
@using MultipleModelInOneView;
@model ViewModel

3. Using ViewData:
==================
Controller Code:
----------------
public ActionResult IndexViewData()
{
ViewBag.Message = "Welcome to my demo!";
ViewData["Teachers"] = GetTeachers();
ViewData["Students"] = GetStudents();
return View();
}
View Code:
----------
@using MultipleModelInOneView;
@{
IEnumerable<Teacher> teachers = ViewData["Teachers"] as IEnumerable<Teacher>;
IEnumerable<Student> students = ViewData["Students"] as IEnumerable<Student>;
}

4. Using ViewBag:
=================
Controller Code:
----------------
public ActionResult IndexViewBag()
{
ViewBag.Message = "Welcome to my demo!";
ViewBag.Teachers = GetTeachers();
ViewBag.Students = GetStudents();
return View();
}
View Code:
----------
@using MultipleModelInOneView;
<p><b>Teacher List</b></p>
@foreach (Teacher teacher in ViewBag.Teachers)
{
}
<p><b>Student List</b></p>
@foreach (Student student in ViewBag.Students)
{
}

5. Using Tuple:
===============
Controller Code:
----------------
public ActionResult IndexTuple()
{
ViewBag.Message = "Welcome to my demo!";
var tupleModel = new Tuple<List<Teacher>, List<Student>>(GetTeachers(),
GetStudents());
return View(tupleModel);
}
View Code:
----------
@using MultipleModelInOneView;
@model Tuple <List<Teacher>, List <Student>>
<p><b>Teacher List</b></p>
@foreach (Teacher teacher in Model.Item1)
{
}
<p><b>Student List</b></p>
@foreach (Student student in Model.Item2)
{
}

6. Using Render Action Method:


==============================
Controller Code:
----------------
public ActionResult PartialView()
{
ViewBag.Message = "Welcome to my demo!";
return View();
}
/// Render Teacher List
public PartialViewResult RenderTeacher()
{
return PartialView(GetTeachers());
}
// Render Student List
public PartialViewResult RenderStudent()
{
return PartialView(GetStudents());
}
View Code:
----------
@{
ViewBag.Title = "PartialView";
<div>
@{
Html.RenderAction("RenderTeacher");
Html.RenderAction("RenderStudent");
}
</div>
RenderTeacher.cshtml:
---------------------
@model IEnumerable<MultipleModelInOneView.Teacher>
<p><b>Teacher List</b></p>
@foreach (Teacher teacher in Model)
{
}
RenderStudent.cshtml:
---------------------
@model IEnumerable<MultipleModelInOneView.Student>
<p><b>Student List</b></p>
@foreach (Student student in Model)
{
}
===================================================================================
==================================
Q) Difference between Asp.Net WebForm and Asp.Net MVC?
Asp.Net WebForm:
----------------
1. Every page(Login.aspx) has its own controller(Login.aspx.cs).
2. Because of above problem UI and logic code are tightly coupled.
3. View page(Login.aspx) size is big.
4. It supports only one view engine(aspx) OR Asp.Net Web Form follows Web Forms
Syntax.
5. Asp.Net Web Form has server controls.
6. Asp.Net Web Form has Master Pages for consistent look and feels.
7. Asp.Net Web Form has built-in data controls and best for rapid development with
powerful data access.
8. Asp.Net Web Form is not Open Source.
9. Asp.Net Web Form has file-based URLs means file name exist in the URLs must have
its physically existence.

Asp.Net MVC:
------------
1. Every page/view has only one controller.
2. Because of above thing UI and logic code are loosly coupled.
3. View page(Login.cshtml) size is very small compare to aspx page.
4. It supports mutiple view engines by default Razor OR Asp.Net MVC follow
customizable syntax(Razor as default).
5. Asp.Net MVC has html helpers.
6. Asp.Net MVC has Layouts for consistent klook and feels.
7. Asp.Net MVC is lightweight, provide full control over markup and support many
features that allow fast & agile development. Hence it is best for developing
interactive web application with latest web standards.
8. Asp.Net Web MVC is an Open Source.
9. 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.
===================================================================================
==================================
Q) Difference between ViewData vs ViewBag vs TempData vs Session in ASP.NET MVC?
1. ViewData:
------------
1. ViewData is derived from the ViewDataDictionary class and is basically a
Dictionary object i.e. Keys and Values where Keys are String while Values will be
objects.
public ViewDataDictionary ViewData { get; set; }
2. ViewData is a property of ControllerBase class.
3. ViewData is used to pass data from controller to corresponding view.
4. It�s life lies only during the current request.
5. If redirection occurs then it�s value becomes null.
6. While retrieving, the data it needs to be Type Casted to its original type as
the data is stored as objects and it also requires NULL checks while retrieving.
7. ViewData is Faster than ViewBag.

2. ViewBag:
-----------
1. ViewBag is a dynamic property that takes advantage of the new dynamic features
in C# 4.0.
2. It is same as ViewData and also used to pass data from controller to
corresponding view.
public Object ViewBag { get; }
3. ViewBag is a property of ControllerBase class.
4. It�s life also lies only during the current request.
5. If redirection occurs then it�s value becomes null.
6. While retrieving, there is no need for Type Casting data.
7. ViewBag is slower than ViewData.
3. TempData:
------------
1. TempData is a dictionary object that is derived from TempDataDictionary class
and stored in short lives session.
public TempDataDictionary TempData { get; set; }
2. TempData is a property of ControllerBase class.
3. TempData can be used for passing value from Controller to View and also from
Controller to Controller
4. It�s life is very short and lives only till the target view is fully loaded.
5. While retrieving, the data it needs to be Type Casted to its original type as
the data is stored as objects
and it also requires NULL checks while retrieving.
6. It is used to store only one time messages like error messages, validation
messages.

Keep() & Peek():


----------------
=>Once "TempData" is read in the current request it's not available in the
subsequent request.
=>If we want "TempData" to be read and also available in the subsequent request
then after reading we need to call "Keep" method as shown in the code below.
@TempData["MyData"];

=>The more shortcut way of 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();

4. Session:
-----------
1. In ASP.NET MVC, Session is a property of Controller class whose type is
HttpSessionStateBase.
public HttpSessionStateBase Session { get; }
Session Disable in Controler Level:-
[SessionState(SessionStateBehavior.Disabled)]
2. Session is also used to pass data within the ASP.NET MVC application untill
closes the browser and Unlike TempData, it persists for its expiration time(by
default session expiration time is 20 minutes but it can be increased).
3. Session is valid for all requests, not for a single redirect.
4. It�s also required typecasting for getting data and check for null values to
avoid error.
===================================================================================
==================================
Q) What are the advantages of MVC?
Benefits of MVC:-
-----------------
=> Multiple view support:-
Due to the separation of the model from the view, the user interface can display
multiple views of the same data at the same time.

=> Change Accommodation:-


User interfaces tend to change more frequently than business rules (different
colors, fonts, screen layouts, and levels of support for new devices such as cell
phones or PDAs) because the model does not depend on the views, adding new types of
views to the system generally does not affect the model. As a result, the scope of
change is confined to the view.

=> SoC � Separation of Concerns:-


Separation of Concerns is one of the core advantages of ASP.NET MVC . The MVC
framework provides a clean separation of the UI, Business Logic, Model or Data.

=> More Control:-


The ASP.NET MVC framework provides more control over HTML, JavaScript and CSS than
the traditional Web Forms.

=> Testability:-
ASP.NET MVC framework provides better testability of the Web Application and good
support for the test driven development too.

=> Lightweight:-
ASP.NET MVC framework doesn�t use View State and thus reduces the bandwidth of the
requests to an extent.

=> Full features of ASP.NET:-


One of the key advantages of using ASP.NET MVC is that it is built on top of
ASP.NET framework and hence most of the features of the ASP.NET like membership
providers, roles, etc can still be used.
===================================================================================
==================================
Q) Explain MVC application life cycle?
=>Any web application has two main execution steps, first understanding the request
and depending on the type of the request sending out appropriate response.
=>MVC application life cycle is not different it has two main phases, first
creating the request object and second sending our response to the browser.

=> Creating the request object:


-------------------------------
The request object creation has four major steps. The following is the detailed
explanation of the same.

Step 1: Fill route


MVC requests are mapped to route tables which in turn specify which controller and
action to be invoked. So if the request is the first request the first thing is to
fill the route table with routes collection. This filling of route table happens in
the global.asax file.

Step 2: Fetch route


Depending on the URL sent �UrlRoutingModule� searches the route table to create
�RouteData� object which has the details of which controller and action to invoke.

Step 3: Request context created


The �RouteData� object is used to create the �RequestContext� object.

Step 4: Controller instance created


This request object is sent to �MvcHandler� instance to create the controller class
instance. Once the controller class object is created it calls the �Execute� method
of the controller class.

=> Creating Response object:-


-----------------------------
This phase has two steps executing the action and finally sending the response as a
result to the view.
===================================================================================
==================================
Q) List out different return types of a controller action method?
There are total nine return types we can use to return results from controller to
view.
The base type of all these result types is ActionResult.

=> ViewResult (View): This return type is used to return a webpage from an action
method.
=> PartialviewResult (Partialview): This return type is used to send a part of a
view which will be rendered in another view.
=> RedirectResult (Redirect): This return type is used to redirect to any other
controller and action method depending on the URL.
=> RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is
used when we want to redirect to any other action method.
=> ContentResult (Content): This return type is used to return HTTP content type
like text/plain as the result of the action.
=> JsonResult (json): This return type is used when we want to return a JSON
message.
=> JavascriptResult (javascript): This return type is used to return JavaScript
code that will run in browser.
=> FileResult (File): This return type is used to send binary output in response.
=> EmptyResult: This return type is used to return nothing (void) in the result.

===================================================================================
==================================
Q) Explain what is the difference between View and Partial View?
View:-
------
=> It contains the layout page.
=> Before any view is rendered, viewstart page is rendered.
=> View might have markup tags like body, html, head, title, meta etc.
=> View is not lightweight as compare to Partial View.

Partial View:-
--------------
=> It does not contain the layout page.
=> Partial view does not verify for a viewstart.cshtml.We cannot put common code
for a partial view within the viewStart.cshtml.page.
=> Partial view is designed specially to render within the view and just because of
that it does not consist any mark up.
=> We can pass a regular view to the RenderPartial method.
===================================================================================
==================================
Q) What are Partial Views?
A partial view is a view that is rendered within another view. The HTML output
generated by executing the partial view is rendered into the calling (or parent)
view. Like views, partial views use the .cshtml file extension.

Note:-
Partial views are similar to user controls.

When Should I Use Partial Views?


--------------------------------
Partial views are an effective way of breaking up large views into smaller
components. They can reduce duplication of view content and allow view elements to
be reused. Common layout elements should be specified in _Layout.cshtml. Non-layout
reusable content can be encapsulated into partial views.

Referencing a Partial View:-


----------------------------
From within a view page, there are several ways in which you can render a partial
view. The simplest is to use Html.Partial, which returns an IHtmlString and can be
referenced by prefixing the call with @:
@Html.Partial("AuthorPartial")

The PartialAsync method is available for partial views containing asynchronous code
(although code in views is generally discouraged):
@await Html.PartialAsync("AuthorPartial")

You can render a partial view with RenderPartial. This method doesn't return a
result; it streams the rendered output directly to the response. Because it doesn't
return a result, it must be called within a Razor code block (you can also call
RenderPartialAsync if necessary):
@{
Html.RenderPartial("AuthorPartial");
}
Because it streams the result directly, RenderPartial and RenderPartialAsync may
perform better in some scenarios. However, in most cases it's recommended you use
Partial and PartialAsync.

Accessing Data From Partial Views:-


-----------------------------------
When a partial view is instantiated, it gets a copy of the parent view's ViewData
dictionary. Updates made to the data within the partial view are not persisted to
the parent view. ViewData changed in a partial view is lost when the partial view
returns.

You can pass an instance of ViewDataDictionary to the partial view:


@Html.Partial("PartialName", customViewData)

You can also pass a model into a partial view. This can be the page's view model,
or some portion of it, or a custom object. Simply pass in the model as the second
parameter when calling Partial/PartialAsync or RenderPartial/RenderPartialAsync:+
@Html.Partial("PartialName", viewModel)

You can pass an instance of ViewDataDictionary and a view model to a partial view:
@Html.Partial("PartialName", viewModel, customViewData)
===================================================================================
==================================
Q) Difference between Html.Partial() and Html.RenderPartial() in ASP.NET MVC:
Html.Partial():-
----------------
=> Html.Partial returns html string.
=> Html.Partial injects html string of the partial view into main view.
=> Performance is slow.
=> Html.Partial() need not to be inside the braces.

Html.RenderPartial():-
----------------------
=> Html.RenderPartial returns void.
=> Html.RenderPartial writes html in response stream.
=> Perform faster than HtmlPartial().
=> Html.RenderPartial must be inside braces @{ }.
===================================================================================
==================================
Q) How to precompile razor view in ASP.NET MVC?
By default, razor views are not compiled with project. It will compile at runtime.

Problem:
Razor view will not give you compile time error if you have used wrong property
name or property name changes. It throws runtime exception.
Solution:
You can turn on compilation in your project file.
Open .csproj file in notepad. Find <mvcbuildviews> in .csproj file. Change
<MvcBuildViews>false</MvcBuildViews> to <MvcBuildViews>true</MvcBuildViews>.
===================================================================================
==================================
Q) What is RouteData in MVC?
RouteData is a property of base Controller class, so RouteData can be accessed in
any controller. RouteData contains route information of a current request. You can
get the controller, action or parameter information using RouteData as shown below.

RouteData in MVC:-
------------------
public class StudentController : Controller
{
public ActionResult Index(int? id, string name, int? standardId)
{
var controller = RouteData.Values["controller"];
var action = RouteData.Values["action"];

id = (int)RouteData.Values["id"];
name = (string)RouteData.Values["name"];
standrdId = (int)RouteData.Values["standardId"];

var area = RouteData.DataTokens["areaname"];

return View();
}
}
===================================================================================
==================================
Q) Difference between RenderBody and RenderSection in ASP.NET MVC:
RenderBody():-
--------------
=> RenderBody must be present in the layout view.
=> RenderBody renders all the content of child view which is not wrapped in named
section.
=> Multiple RenderBody() method is NOT allowed in a single layout view.
=> RenderBody() method does not include any parameter.

RenderSection():-
-----------------
=> RenderSection method is optional.
=> RenderSection renders only a part child view that is wrapped under named
section.
=> Multiple RenderSection() method is allowed in a single layout view.
=> RenderSection() method includes boolean parameter "required" which makes the
section optional or mandatory. If required parameter is true then the child view
must contain the section.
===================================================================================
==================================
Q) Explain attribute based routing in MVC?
In ASP.NET MVC 5.0 we have a new attribute route,cBy using the "Route" attribute we
can define the URL structure. For example in the below code we have decorated the
"GotoAbout" action with the route attribute. The route attribute says that the
"GotoAbout" can be invoked using the URL structure "Users/about".
public class HomeController: Controller
{
[Route("Users/about")]
publicActionResultGotoAbout()
{
return View();
}
}
===================================================================================
==================================
Q) What is Razor in MVC?
Razor is one of the view engine supported in ASP.NET MVC. Razor allows you to write
mix of HTML and server side code using C# or Visual Basic. Razor view with visual
basic syntax has .vbhtml file extension and C# syntax has .cshtml file extension.

Razor syntax has following Characteristics:


-------------------------------------------
Compact: Razor syntax is compact which enables you to minimize number of characters
and keystrokes required to write a code.
Easy to Learn: Razor syntax is easy to learn where you can use your familiar
language C# or Visual Basic.
Intellisense: Razor syntax supports statement completion within Visual Studio.
===================================================================================
==================================
Q) Differences between Razor and ASPX View Engine in MVC?
Razor View Engine:-
-------------------
=> The namespace used by the Razor View Engine is System.Web.Razor
=> The file extensions used by the Razor View Engine are different from a web form
view engine. It uses cshtml with C# and vbhtml with vb for views, partial view,
templates and layout pages.
=> The Razor View Engine is an advanced view engine that was introduced with MVC
3.0. This is not a new language but it is markup.
=> Razor has a syntax that is very compact and helps us to reduce typing.
=> The Razor View Engine uses @ to render server-side content.
=> By default all text from an @ expression is HTML encoded.
=> Razor does not require the code block to be closed, the Razor View Engine parses
itself and it is able to decide at runtime which is a content element and which is
a code element.
=> The Razor View Engine prevents Cross Site Scripting (XSS) attacks by encoding
the script or HTML tags before rendering to the view.
=> The Razor Engine supports Test Driven Development (TDD).
=> Razor uses "@* … *@" for multiline comments.
=> There is only three transition characters with the Razor View Engine.

ASPX View Engine (Web form view engine):-


-----------------------------------------
=> The namespace used by the ASPX View Engine is System.Web.Mvc.WebFormViewEngine
=> The file extensions used by the Web Form View Engines are like ASP.Net web
forms. It uses the ASPX extension to view the aspc extension for partial views or
User Controls or templates and master extensions for layout/master pages.
=> A web form view engine is the default view engine and available from the
beginning of MVC
=> The web form view engine has syntax that is the same as an ASP.Net forms
application.
=> A web form view engine requires the code block to be closed properly otherwise
it throws a runtime exception.
=> The ASPX/web form view engine uses "<%= %>" or "<%: %>" to render server-side
content.
=> There is a different syntax ("<%: %>") to make text HTML encoded.
=> A web form view engine requires the code block to be closed properly otherwise
it throws a runtime exception.
=> A web form View engine does not prevent Cross Site Scripting (XSS) attack.
=> Web Form view engine does not support Test Driven Development (TDD) because it
depends on the System.Web.UI.Page class to make the testing complex.
=> The ASPX View Engine uses "<!--...-->" for markup and "/* … */" for C# code.
=> There are only three transition characters with the Razor View Engine.
===================================================================================
==================================
Q) Explain Areas in MVC?
Areas was introduced in Asp.net MVC2 which allow us to organize models, views, and
controllers into separate functional sections of the application, such as
administration, billing, customer support, and so on. This is very helpful in a
large web application, where all the controllers, views, and models have a single
set of folders and that become difficult to manage.

Each MVC area has its own folder structure which allow us to keep separate
controllers, views, and models. This also helps the multiple developers to work on
the same web application without interfere to one another.
Registering Area Before working with area, make sure you have registered your area
with in the Application_Start method in Global.asax as shown below.

protected void Application_Start()


{
//Register all application Areas
AreaRegistration.RegisterAllAreas();

WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}

Note:-
Always remember the order of registering the Areas must be on top, so that all of
the settings, filters and routes registered for the applications will also apply on
the Areas.
===================================================================================
==================================
Q) Explain the concept of MVC Scaffolding?
Scaffolding is a technique used by many MVC frameworks like ASP.NET MVC, Ruby on
Rails, Cake PHP and Node.JS etc., to generate code for basic CRUD (create, read,
update, and delete) operations against your database effectively. Further you can
edit or customize this auto generated code according to your need.

Scaffolding consists of page templates, entity page templates, field page


templates, and filter templates. These templates are called Scaffold templates and
allow you to quickly build a functional data-driven Website.

How Scaffold templates works in ASP.NET MVC:-


---------------------------------------------
Scaffold templates are used to generate code for basic CRUD operations within your
ASP.NET MVC applications against your database with the help Entity Framework.
These templates use the Visual Studio T4 templating system to generate views for
basic CRUD operations with the help of Entity Framework.
===================================================================================
==================================
Q) What is Bundling and Minification in MVC?
Bundling and minification are two new techniques introduced to improve request load
time. It improves load time by reducing the number of requests to the server and
reducing the size of requested assets (such as CSS and JavaScript).

=> Bundling: It lets us combine multiple JavaScript (.js) files or multiple


cascading style sheet (.css) files so that they can be downloaded as a unit, rather
than making individual HTTP requests.

=> Minification: It squeezes out whitespace and performs other types of compression
to make the downloaded files as small as possible. At runtime, the process
identifies the user agent, for example IE, Mozilla, etc. and then removes whatever
is specific to Mozilla when the request comes from IE.
===================================================================================
==================================
Q) What is difference between MVC and Web Forms?
ASP.Net MVC:-
--------------
=> View and logic are separate, it has separation of concerns theory. MVC 3 onwards
has .aspx page as .cshtml.
=> Introduced concept of routing for route based URL. Routing is declared in
Global.asax for example.
=> Support Razor syntax as well as .aspx
=> State management handled via Tempdata, ViewBag, and View Data. Since the
controller and view are not dependent and also since there is no view state concept
in ASP.NET, MVC keeps the pages lightweight.
=> Partial Views
=> HTML Helpers
=> Multiple pages can have the same controller to satisfy their requirements. A
controller may have multiple Actions (method name inside the controller class).
=> Unit Testing is quite easier than ASP.Net Web forms Since a web form and code
are separate files.
=> layouts

ASP.Net Web Forms:-


-------------------
=> No separation of concerns; Views are tightly coupled with logic (.aspx.cs /.vb
file).
=> File-based routing .Redirection is based on pages.
=> Support web forms syntax only.
=> State management handled via View State. Large viewstate, in other words
increase in page size.
=> User Controls
=> Server Controls
=> Each page has its own code, in other words direct dependency on code. For
example Sachin.aspx is dependent on => Sachin.aspx.cs (code behind) file.
=> Direct dependency, tight coupling raises issues in testing.
=> Master pages
===================================================================================
==================================
Q) What is Data Annotations for Model Validation in ASP.NET MVC?
Data validation is a key aspect for developing web application. In Asp.net MVC, we
can easily apply validation to web application by using Data Annotation attribute
classes to model class. Data Annotation attribute classes are present in
System.ComponentModel.DataAnnotations namespace and are availlable to Asp.net
projects like Asp.net web application & website, Asp.net MVC, Web forms and also to
Entity framework orm models.

Data Annotations help us to define the rules to the model classes or properties for
data validation and displaying suitable messages to end users.
Data Annotation Validator Attributes:
-------------------------------------
DataType
Specify the datatype of a property

DisplayName
specify the display name for a property.

DisplayFormat
specify the display format for a property like different format for Date proerty.

Required
Specify a property as required.

ReqularExpression
validate the value of a property by specified regular expression pattern.

Range
validate the value of a property with in a specified range of values.

StringLength
specify min and max length for a string property.

MaxLength
specify max length for a string property.

Bind
specify fields to include or exclude when adding parameter or form values to model
properties.

ScaffoldColumn
specify fields for hiding from editor forms.

Designing the model with Data Annotations :-


--------------------------------------------
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Employee.Models
{
[Bind(Exclude = "EmpId")]
public class Employee
{
[ScaffoldColumn(false)]
public int EmpId { get; set; }

[DisplayName("Employee Name")]
[Required(ErrorMessage = "Employee Name is required")]
[StringLength(100,MinimumLength=3)]
public String EmpName { get; set; }

[Required(ErrorMessage = "Employee Address is required")]


[StringLength(300)]
public string Address { get; set; }

[Required(ErrorMessage = "Salary is required")]


[Range(3000, 10000000,ErrorMessage = "Salary must be between 3000 and 10000000")]
public int Salary{ get; set; }

[Required(ErrorMessage = "Please enter your email address")]


[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
[MaxLength(50)]
[RegularExpression(@"[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}", ErrorMessage =
"Please enter correct email")]
public string Email { get; set; }
}
}
Once we have define validation to the model by using data annotations, these are
automatically used by Html Helpers in views. For client side validation to work,
please ensure that below two <SCRIPT> tag references are in the view.

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
===================================================================================
==================================
Q) What is Routing in Asp.Net MVC with example?
Basically, Routing is a pattern matching system that monitor the incoming request
and figure out what to do with that request. At runtime, Routing engine use the
Route table for matching the incoming request's URL pattern against the URL
patterns defined in the Route table. You can register one or more URL patterns to
the Route table at Application_Start event.

How to define route :-


------------------------
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // Route Pattern
new { controller = "Home", action = "Index", id = UrlParameter.Optional } //
Default values for above defined parameters
);
}

protected void Application_Start()


{
RegisterRoutes(RouteTable.Routes);
//To:DO
}

When the routing engine finds a match in the route table for the incoming request's
URL, it forwards the request to the appropriate controller and action. If there is
no match in the route table for the incoming request's URL, it returns a 404 HTTP
status code.

Note :-
Always remember route name should be unique across the entire application. Route
name can�t be duplicate.
===================================================================================
==================================
Q) Difference between Routing and URL Rewriting?
Many developers compare routing to URL rewriting that is wrong. Since both the
approaches are very much different. Moreover, both the approaches can be used to
make SEO friendly URLs. Below is the main difference between these two approaches.
=> URL rewriting is focused on mapping one URL (new url) to another URL (old url)
while routing is focused on mapping a URL to a resource.
=> Actually, URL rewriting rewrites your old url to new one while routing never
rewrite your old url to new one but it map to the original route.
===================================================================================
==================================
Q) State Management techniques in ASP.Net MVC
Client side state management :-
-------------------------------
In client side page management the information is stored on client system. This
information will travel back and forth with every request and response to and from
server.

Advantage :-
------------
The major advantages of having this kind of state management is that it saves a lot
of server memory. we relieve server from the burden of keeping the state related
information.

Disadvantage:-
--------------
It takes more bandwidth as considerable amount of data is traveling back and forth.
Due to this, web page becomes slow to load.
The main draw back is it creates security issue for sensitive information like
passwords, credit card numbers etc.

ASP.NET provides following types of client side methods to manage state in web
applications.
=> Hidden Field
=> Cookies
=> Query Strings
=> View Data
=> View Bag
=> Temp Data

Server side state management :-


-------------------------------
In server side state management we keep all the information in server memory.

Advantage:-
-----------
The major advantages of having this kind of state management is that it secure
user�s confidential and sensitive information.

Disadvantage:-
--------------
The downside of this is it usage more server memory.

ASP.NET provides following types of Server side methods to manage state in web
applications.
=> Session state
=> Profile Properties
=> Cache

Profile Properties:-
--------------------
ASP.NET provides profile properties, which allows us to store user customized data
as per user's convenient appearance. It is similar to session state, except profile
data is not lost when a user's session expires. The profile properties feature uses
to store in a persistent format and associated with an individual user.

To use profile properties, we need to first enable profiles by modifying the


configuration file Web.Config. Where we need to specify a profile provider, which
is the underlying class that performs the low-level tasks of storing and retrieving
profile data. We can store user profile data in SQL server.

<profile defaultProvider="DefaultProfileProvider">

<providers>

<add name=�DefaultProfileProvider�
type=�System.Web.Providers.DefaultProfileProvider, System.Web.Providers,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35�
connectionStringName=�DefaultConnection� applicationName=�/� />

</providers>

</profile>

Cache:-
-------
Caching provides a way of storing frequently accessed data and reusing that data.
It is an effective way for improving web application�s performance. The output
cache enables us to cache the content returned by a controller action. That way,
the same content does not need to be generated each and every time the same
controller action is invoked.

The OutputCache filter allow to cache the data that is output of an action method.
By default, this attribute filter cache the data till 60 seconds. After 60 sec,
Asp.Net MVC will execute the action method again and cache the output again. We can
enable the output caching for an action method or controller by adding an
[OutputCache] attribute as shown below:

[OutputCache(Duration=10, VaryByParam="none")]
public ActionResult Index()
{
return View();
}

OutputCache Filter Parameters:-


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

Parameter Description

CacheProfile Specify the name of the output cache policy which is


defined with in <outputCacheSettings> tag of Web.config.
[OutputCache(CacheProfile = �Short�)]
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name=�Short� duration=�20�/>
</outputCacheProfiles>
</outputCacheSettings>
</caching>

Duration Specify the time in sec to cache the content.


Location Specify the location of the output to be cached. Values: Any,
Client,Downstream, Server, None, or ServerAndClient. By
default location is Any.

[OutputCache(Duration=3600,Location=System.Web.UI.OutputCacheLocation.None)]

NoStore This is used only to protect very sensitive data.


Enable/Disable where to use HTTP Cache- Control.
SqlDependency Specify the database and table name pairs on which the
cache content depends on. The cached data will expire
automatically when the data changes in the database.
VaryByCustom Specify the list of custom strings that the output cache
uses to vary the cache content.

VaryByHeader Specify the semicolon separated list of HTTP header names


that are used to vary the cache content.
VaryByParam Specify the semicolon separated list of form POST or query string
parameters that are used to vary the cache content. If not specified,
the default value is none.
[OutputCache(Duration = 7200, Location =
System.Web.UI.OutputCacheLocation.Client, VaryByParam
= �none�, NoStore = true)]
VaryByContentEncoding Specify the semicolon separated list of character set that
the output cache uses to vary the cache content.
===================================================================================
==================================
Q) It is possible to Render a View inside a View in Asp.Net mvc?
@RenderPage("~/Views/Shared/SampleView.cshtml")
(OR)
[ChildActionOnly]
public ActionResult ActionPartialView(string p1)
{
//code...
return PartialView();
}
@{ Html.RenderAction("Index", "Home"); }
===================================================================================
==================================
Q) Q) what is form authentication and how we use an implement it in asp.net mvc?
Authentication and Authorization:
---------------------------------
Authentication
--------------
Authentication is the process of verifying the identity of a user by obtaining some
sort of credentials and using those credentials to verify the user's identity. If
the credentials are valid, the authorization process starts. Authentication process
always proceeds to Authorization process.

<authentication mode="[Windows|Forms|Passport|None]">
<forms loginUrl="~/MyAccount/Login" timeout="2" />
</authentication>

Authorization
--------------
Authorization is the process of allowing an authenticated users to access the
resources by checking whether the user has access rights to the system.
Authorization helps you to control access rights by granting or denying specific
permissions to an authenticated user.
Type of Authentications:-
--------------------------
Windows authentication:
-----------------------
In this mode, the users are authenticated on their Windows username and password.
This method is least recommended in an internet scenario. In an internet scenario,
we should always use "Forms based authentication".

Forms based authentication:


---------------------------
In this type of authentication, the user will explicitly have to provide his
credentials and these credentials, once verified by the server, will let the user
to log in.

Sample Forms Authentication Code:-


----------------------------------
web.config:-
------------
<authentication mode="Forms">
<forms loginUrl="~/MyAccount/Login" timeout="2" />
</authentication>

Login Action Method:-


----------------------
public ActionResult Login()
{
return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(Login l, string ReturnUrl = "")
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
var user = dc.Users.Where(a => a.Username.Equals(l.Username) &&
a.Password.Equals(l.Password)).FirstOrDefault();
if (user != null)
{
FormsAuthentication.SetAuthCookie(user.Username, l.RememberMe);
if (Url.IsLocalUrl(ReturnUrl))
{
return Redirect(ReturnUrl);
}
else
{
return RedirectToAction("MyProfile", "Home");
}
}
}
ModelState.Remove("Password");
return View();
}

HomeController/MyProfile Action Method:-


----------------------------------------
[AllowAnonymous] //This is for Un-Authorize User //Start page of the
project
public ActionResult Index()
{
return View();
}

[Authorize] // This is for Authorize user


public ActionResult MyProfile()
{
return View();
}

@{
ViewBag.Title = "MyProfile";
}

<h2>MyProfile</h2>

<h3>Welcome @(Request.IsAuthenticated ? HttpContext.Current.User.Identity.Name :


"Guest") - This is for Authorized user </h3>

Layout.cshtml:-
----------------
<body>
<ul class="menu">
<li>@Html.ActionLink("Home","Index","Home")</li>
<li>@Html.ActionLink("My Profile","MyProfile","Home")</li>
<li>
@{
if (Request.IsAuthenticated)
{
using (Html.BeginForm("Logout","MyAccount",
FormMethod.Post,new{ id = "logoutForm"}))
{
<a
href="javascript:document.getElementById('logoutForm').submit()">Logout</a>
}
}
else
{
@Html.ActionLink("Login","Login","MyAccount")
}
}
</li>
</ul>
<div style="height:1px;clear:both"></div>
@RenderBody()

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)
</body>
===================================================================================
==================================
Q) How to Create DropDownList using HtmlHelper in asp.net mvc?
TextBox() & TextArea():-
------------------------
Html.TextBox(string name, string value, object htmlAttributes)
@Html.TextBox("StudentName", null, new { @class = "form-control" })

CheckBox():-
------------
CheckBox(string name, bool isChecked, object htmlAttributes)
@Html.CheckBox("isNewlyEnrolled", true)

RadioButton():-
---------------
RadioButton(string name, object value, bool isChecked, object htmlAttributes
Male: @Html.RadioButton("Gender","Male")
Female: @Html.RadioButton("Gender","Female")

DropDownList():
---------------
Html.DropDownList(string name, IEnumerable<SelectLestItem> selectList, string
optionLabel, object htmlAttributes)
@Html.DropDownList("StudentGender",
new SelectList(Enum.GetValues(typeof(Gender))),
"Select Gender",
new { @class = "form-control" })

TextBoxFor & TextAreaFor:-


--------------------------
TextBoxFor(Expression<Func<TModel,TValue>> expression, object htmlAttributes)
@Html.TextBoxFor(m => m.StudentName, new { @class = "form-control" })

CheckBoxFor:-
-------------
CheckBoxFor(<Expression<Func<TModel,TValue>> expression, object htmlAttributes)
@Html.CheckBoxFor(m => m.isNewlyEnrolled)

RadioButtonFor:-
-----------------
HtmlString RadioButtonFor(<Expression<Func<TModel,TValue>> expression, object
value, object htmlAttributes)
Html.RadioButtonFor() in Razor View
@Html.RadioButtonFor(m => m.Gender,"Male")
@Html.RadioButtonFor(m => m.Gender,"Female")

DropDownListFor:
----------------
Html.DropDownListFor(Expression<Func<dynamic,TProperty>> expression,
IEnumerable<SelectLestItem> selectList, string optionLabel, object htmlAttributes)
@Html.DropDownListFor(m => m.StudentGender,
new SelectList(Enum.GetValues(typeof(Gender))),
"Select Gender")
===================================================================================
==================================
Q) What is Model Binding in ASP.Net MVC?
Model Binding allows you to map and bind the HTTP request data with a model. If you
want to work with the form data, Model Binding makes it easier because the
requested data is submitted automatically into a data model that we specify.
===================================================================================
==================================
Q) Difference Between UpdateModel And TryUpdateModel Function in ASP.NET MVC?
=> UpdateModel() throws an exception, if validation fails, whereas TryUpdateModel()
will never throw an exception.
=> The similarity between both is that the functions are used to update the model
with the form values and perform the validations.
===================================================================================
==================================
Q) Difference between return View() vs return RedirectToAction() vs return
Redirect() vs return RedirectToRoute()?
return View():-
---------------
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hi, Dot Net Tricks";
//Like Server.Transfer() in Asp.Net WebForm
return View("MyIndex");
}

public ActionResult MyIndex()


{
ViewBag.Msg = ViewBag.Message; // Assigned value : "Hi, Dot Net Tricks"
return View("MyIndex");
}
(OR)
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hi, Dot Net Tricks";
//Like Server.Transfer() in Asp.Net WebForm
return MyIndex();
}

public ActionResult MyIndex()


{
ViewBag.Msg = ViewBag.Message; // Assigned value : "Hi, Dot Net Tricks"
return View("MyIndex");
}

return RedirectToAction():-
---------------------------
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hi, Dot Net Tricks";
//Like Response.Redirect() in Asp.Net WebForm
return RedirectToAction("MyIndex");
}

public ActionResult MyIndex()


{
ViewBag.Msg = ViewBag.Message; // Assigned value : Null
return View("MyIndex");
}

return Redirect():-
-------------------
public ActionResult Index()
{
return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hi, Dot Net Tricks";
//Like Response.Redirect() in Asp.Net WebForm
return Redirect("Home/MyIndex");
}

public ActionResult MyIndex()


{
ViewBag.Msg = ViewBag.Message; // Assigned value : Null
return View("MyIndex");
}

return RedirectToRoute():-
--------------------------
Defined Route
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute(
"MyRoute", // Route name
"Account/", // URL
new { controller = "Account", action = "Login"} // Parameter defaults
);

routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "MyIndex", id = UrlParameter.Optional } //
Parameter defaults
);
}
HomeController

public ActionResult Index()


{
return View();
}

[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToRoute("MyRoute");
}
AccountController

public ActionResult Login()


{
return View();
}

Note :-
--------
Return View doesn't make a new requests, it just renders the view without changing
URLs in the browser's address bar.
Return RedirectToAction makes a new requests and URL in the browser's address bar
is updated with the generated URL by MVC.
Return Redirect also makes a new requests and URL in the browser's address bar is
updated, but you have to specify the full URL to redirect
Between RedirectToAction and Redirect, best practice is to use RedirectToAction for
anything dealing with your application actions/controllers. If you use Redirect and
provide the URL, you'll need to modify those URLs manually when you change the
route table.
RedirectToRoute redirects to a specific route defined in the Route table.
===================================================================================
==================================
Q) Caching in Asp.Net MVC with example?
Caching is a most important aspect of high-performance web application. Caching
provides a way of storing frequently accessed data and reusing that data.
Practically, this is an effective way for improving web application�s performance.

Advantage of Caching:-
-----------------------
Reduce hosting server round-trips
When content is cached at the client or in proxies, it cause minimum request to
server.

Reduce database server round-trips


When content is cached at the web server, it can eliminate the database request.

Reduce network traffic


When content is cached at the client side, it it also reduce the network traffic.

Avoid time-consumption for regenerating reusable content


When reusable content is cached, it avoid the time consumption for regenerating
reusable content.

Improve performance
Since cached content reduce round-trips, network traffic and avoid time consumption
for regenerating reusable content which cause a boost in the performance.

Key points about Caching:-


--------------------------
=> Use caching for contents that are accessed frequently.
=> Avoid caching for contents that are unique per user.
=> Avoid caching for contents that are accessed infrequently/rarely.
=> Use the VaryByCustom function to cache multiple versions of a page based on
customization aspects of the request such as cookies, role, theme, browser, and so
on.
=> For efficient caching use 64-bit version of Windows Server and SQL Server.
=> For database caching make sure your database server has sufficient RAM
otherwise, it may degrade the performance.
=> For caching of dynamic contents that change frequently, define a short
cache�expiration time rather than disabling caching.

Output Cache Filter:-


---------------------
The OutputCache filter allow you to cache the data that is output of an action
method. By default, this attribute filter cache the data till 60 seconds. After 60
sec, if a call was made to this action then ASP.NET MVC will cache the output
again.

Enabling Output Caching:-


-------------------------
You can enable the output caching for an action method or controller by adding an
[OutputCache] attribute as shown below:

[OutputCache(Duration=20, VaryByParam="none")]
public ActionResult Index()
{
ViewBag.Message = DateTime.Now.ToString();
return View();
}

The output of the Index() action method will be cached for 20 seconds. If you will
not defined the duration, it will cached it for by default cache duration 60 sec.

Output Caching Location:-


-------------------------
=> By default, content is cached in three locations: the web server, any proxy
servers, and the user's browser. You can control the content's cached location by
changing the location parameter of the OutputCache attribute to any of the
following values: Any, Client,Downstream, Server, None, or ServerAndClient.
=> By default, the location parameter has the value Any which is appropriate for
most the scenarios. But some times there are scenarios when you required more
control over the cached data.
=> Suppose you want to cache the logged in use information then you should cached
the data on client browser since this data is specific to a user. If you will
cached this data on the server, all the user will see the same information that is
wrong.
=> You should cache the data on the server which is common to all the users and is
sensitive.

Configure Cache Location:-


--------------------------
For configuring the cache location, you need to add the System.Web.UI namespace on
your controller. You can cached the user's personal information in his browser like
as below.

[OutputCache(Duration = 7200, Location = OutputCacheLocation.Client, VaryByParam =


"none", NoStore = true)]
public ActionResult Index()
{
ViewBag.Message = "Welcome : " + User.Identity.Name;
return View();
}
===================================================================================
==================================
Q) How to Resolve Ambiguous Controller Error by routes in ASP.NET MVC?
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // Route Pattern
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, //
Default values for parameters
new[] { "Mvc4_RouteConstraints"});
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // Route Pattern
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, //
Default values for parameters
new[] { "Mvc4_Route"});
);
===================================================================================
==================================
Q) Route Constraints in Asp.Net MVC with example?
Creating Route Constraints
Suppose we have defined the following route in our application and you want to
restrict the incoming request url with numeric id only.Now let's see how to do it
with the help of regular expression.

Restrict to numeric id only:-


-----------------------------
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // Route Pattern
new { controller = "Home", action = "Index", id = UrlParameter.Optional }, //
Default values for parameters
new { id = @"\d+" } //Restriction for id
);
===================================================================================
==================================
Q) How to Enable and Disable Client-Side Validation in MVC?
Enable Client-Side Validation in MVC:-
--------------------------------------
For enabling client side validation, we required to include the jQuery min,
validate & unobtrusive scripts in our view or layout page in the following order.
<script src="@Url.Content("~/Scripts/jquery-1.6.1.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")"
type="text/javascript"></script>

Enabling and Disabling Client-Side Validation at Application Level:-


--------------------------------------------------------------------
We can enable and disable the client-side validation by setting the values of
ClientValidationEnabled & UnobtrusiveJavaScriptEnabled keys true or false. This
setting will be applied to application level.
<appSettings>
<add key="ClientValidationEnabled" value="true"/>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>
(OR)
protected void Application_Start()
{
//Enable or Disable Client Side Validation at Application Level
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}

Enabling and Disabling Client-Side Validation for Specific View:-


-----------------------------------------------------------------
We can also enable or disable client-side validation for a specific view. For this
we required to enable or disable client side validation inside a Razor code block
as shown below. This option will overrides the application level settings for that
specific view.
@model MvcApp.Models.Appointment
@{
ViewBag.Title = "Make A Booking";
HtmlHelper.ClientValidationEnabled = false;
}
===================================================================================
==================================
Q) How Removing the Web Form View Engine for better performance of Razor View
Engine?
protected void Application_Start()
{
//Remove All Engine
ViewEngines.Engines.Clear();
//Add Razor Engine
ViewEngines.Engines.Add(new RazorViewEngine());
}
===================================================================================
==================================
Q) How to apply Inline CSS and Styles with Html Helpers in MVC3 Razor?
Apply CSS Class to Html Helpers:-
---------------------------------
Suppose above css class is defined in the external style sheet. Now you want to
apply this class to html helpers then we need to add class name by using @class
like as :
@Html.TextBox("Name", new { @class="inputclass" })
@Html.TextBoxFor(model => model.Name, new { @class="inputclass" })

Apply Inline CSS to Html Helpers:-


----------------------------------
We can also add inline css to html helpers by using style like as :
@Html.TextBoxFor(model => model.Name, new { style="width:100px;height:25px" })
@Html.TextBox("Name", new { style="width:100px;height:25px" })
===================================================================================
==================================
Q) How to Gett all table cell <td> values?
$("#submit").on('click', function (e) {
e.preventDefault();
var data = $("#attendees tr.data").map(function (index, elem) {
var ret = [];
$('.inputValue', this).each(function () {
var d = $(this).val() || $(this).text();
ret.push(d);
});
return ret;
});
console.log(data);
});

output:-
--------
["Students Name", "N/A", "N/A", "0", "0", "Yes", "Cash/Credit", prevObject:
init[1], context: document]

(OR)

var $row = $(this).closest("tr"), // Finds the closest row <tr>


$tds = $row.find("td"); // Finds all children <td> elements
$.each($tds, function() { // Visits every single <td> element
console.log($(this).text()); // Prints out the text within the <td>
});

Useful methods
---------------
.closest() - get the first element that matches the selector
.parent() - get the parent of each element in the current set of matched elements
.parents() - get the ancestors of each element in the current set of matched
elements
.children() - get the children of each element in the set of matched elements
.siblings() - get the siblings of each element in the set of matched elements
.find() - get the descendants of each element in the current set of matched
elements
.next() - get the immediately following sibling of each element in the set of
matched elements
.prev() - get the immediately preceding sibling of each element in the set of
matched elements
===================================================================================
==================================
Q) Sample Route Example?
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Profile", action = "Home", id =
UrlParameter.Optional }
);
===================================================================================
==================================
Q) Sample Jquery Ajax Call Function in ASP.NET MVC?
$( document ).ready(function() {
$( "#target" ).click(function() {
$.ajax({
type: 'POST',
url: '/ControllerName/ActionMethodName',
data: { 'foo': 'bar'},
success: function(msg){
alert('wow' + msg);
},
error: function(errorMsg){
alert('wow' + errorMsg);
}
})
});
});
===================================================================================
==================================
Q) How to create Dynamic Table in ASP.NET MVC using Jquery?
//Crate table html tag
var table = $("<table class='table table-bordered table-striped'
id='renewaldomaininfotable'></table>").appendTo("#renewals-domains-list");
//Create table header row
var tableHeader = $("<thead></thead").appendTo(table);
var rowHeader = $("<tr></tr>").appendTo(tableHeader);
$("<td></td>").text("SNO").appendTo(rowHeader);
$("<td></td>").text("Domain Name").appendTo(rowHeader);
$("<td></td>").text("Registrant").appendTo(rowHeader);
$("<td></td").text("Expiry Date").appendTo(rowHeader);
$("<td></td>").text("Expiry Due Days").appendTo(rowHeader)
if (response.Renewals.length >= 0) {
var tableBody = $("<tbody></tbody").appendTo(table);
for (var i = 0; i < response.Renewals.length; i++) {
var row = $("<tr
style='height:25px'></tr>").appendTo(tableBody);
$("<td></td>").text(i + 1).appendTo(row);
$
("<td></td>").text(response.Renewals[i].DomainName).appendTo(row);
$
("<td></td>").text(response.Renewals[i].Registrant).appendTo(row);
$
("<td></td>").text(response.Renewals[i].ExpiryDate).appendTo(row);
$
("<td></td>").text(response.Renewals[i].ExpiryDueDays).appendTo(row);
};
===================================================================================
==================================
Q) What is the difference between each version of MVC 2, 3, 4, 5 and 6?
MVC 6:
------
ASP.NET MVC and Web API has been merged in to one.
Dependency injection is inbuilt and part of MVC.
Side by side - deploy the runtime and framework with your application
Everything packaged with NuGet, Including the .NET runtime itself.
New JSON based project structure.
No need to recompile for every change. Just hit save and refresh the browser.
Compilation done with the new Roslyn real-time compiler.
vNext is Open Source via the .NET Foundation and is taking public contributions.
vNext (and Rosyln) also runs on Mono, on both Mac and Linux today.

MVC 5:
------
Attribute based routing
Asp.Net Identity
Bootstrap in the MVC template
Authentication Filters
Filter overrides
One ASP.NET

MVC 4:
------
ASP.NET Web API
Refreshed and modernized default project templates
New mobile project template
Many new features to support mobile apps
Enhanced support for asynchronous methods

MVC 3:
------
Razor
Readymade project templates
HTML 5 enabled templates
Support for Multiple View Engines
JavaScript and Ajax
Model Validation Improvements
===================================================================================
==================================
Q) Difference between HttpGet and HttpPost Method?
Http GET method:-
-----------------
-> GET - Requests data from a specified resource
-> An hyperlink or anchor tag that points to an action will ALWAYS be an HttpGet.
-> Data is submitted as a part of url.
-> It is not secure but fast and quick.
-> Data is limited to max length of query string.
-> It is good when you want user to bookmark page.
-> Data is visible to the user as it posts as query string.

Http POST method:-


------------------
-> POST - Submits data to be processed to a specified resource
-> A Submit button will always initiate an HttpPost request.
-> Data is submitted in http request body.
-> It is more secured but slower as compared to GET.
-> It can post unlimited form variables.
-> It is advisable for sending critical data which should not visible to users.
-> Data is not visible in the url.
==================================================COMPLETED========================
==================================

===================================================================================
==================================
LINQ:
=====

Classification Standard Query Operators


-----------------------------------------------------------------------------------
----------------------------------
Filtering Where, OfType
Sorting OrderBy, OrderByDescending, ThenBy, ThenByDescending,
Reverse
Grouping GroupBy, ToLookup
Join GroupJoin, Join
Projection Select, SelectMany
Aggregation Aggregate, Average, Count, LongCount, Max, Min, Sum
Quantifiers All, Any, Contains
Elements ElementAt, ElementAtOrDefault, First, FirstOrDefault, Last,
LastOrDefault, Single, SingleOrDefault
Set Distinct, Except, Intersect, Union
Partitioning Skip, SkipWhile, Take, TakeWhile
Concatenation Concat
Equality SequenceEqual
Generation DefaultEmpty, Empty, Range, Repeat
Conversion AsEnumerable, AsQueryable, Cast, ToArray, ToDictionary, ToList

ALL SAMPLE LINQ QURIES WITH EXAMPLES:


--------------------------------------
var filteredResult = studentList.Where(s => s.Age > 12 && s.Age < 20);
var stringResult = mixedList.OfType<string>();
var studentsInAscOrder = studentList.OrderBy(s => s.StudentName);
var studentsInDescOrder = studentList.OrderByDescending(s => s.StudentName);
var thenByResult = studentList.OrderBy(s => s.StudentName).ThenBy(s => s.Age);
var thenByDescResult = studentList.OrderBy(s => s.StudentName).ThenByDescending(s
=> s.Age);
var groupedResult = studentList.GroupBy(s => s.Age);
var lookupResult = studentList.ToLookup(s => s.age);
var selectResult = studentList.Select(s => new { Name = s.StudentName , Age = s.Age
});
bool areAllStudentsTeenAger = studentList.All(s => s.Age > 12 && s.Age < 20);
bool isAnyStudentTeenAger = studentList.Any(s => s.age > 12 && s.age < 20);
bool result = intList.Contains(10); // returns false
var avgAge = studentList.Average(s => s.Age);
var numOfStudents = studentList.Count();
var oldest = studentList.Max(s => s.Age);
var oldest = studentList.Min(s => s.Age);
var sumOfAge = studentList.Sum(s => s.Age);
var collection3 = collection1.Concat(collection2);
var distinctList1 = strList.Distinct();
var result = strList1.Except(strList2);
var result = strList1.Intersect(strList2);
var result = strList1.Union(strList2);
var newList = strList.Skip(2);
var newList = strList.Take(2);
var innerJoin = studentList.Join(// outer sequence
standardList, // inner sequence
student => student.StandardID, // outerKeySelector
standard => standard.StandardID, // innerKeySelector
(student, standard) => new // result selector
{
StudentName = student.StudentName,
StandardName = standard.StandardName
});
var groupJoin = standardList.GroupJoin(studentList, //inner sequence
std => std.StandardID, //outerKeySelector
s => s.StandardID, //innerKeySelector
(std, studentsGroup) => new // resultSelector
{
Students = studentsGroup,
StandarFulldName = std.StandardName
});
Using LET Keyword:
------------------
var lowercaseStudentNames = from s in studentList
let lowercaseStudentName = s.StudentName.ToLower()
where lowercaseStudentName.StartsWith("r")
select lowercaseStudentName;
Using INTO Keyword:
-------------------
var teenAgerStudents = from s in studentList
where s.age > 12 && s.age < 20
select s
into teenStudents
where teenStudents.StudentName.StartsWith("B")
select teenStudents;

===================================================================================
==================================
Example Data:
-------------
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 },
new Student() { StudentID = 6, StudentName = "Ram" , Age = 18 }
};

Filtering Operators - Where & OfType:


-------------------------------------
Where:-
=====
var filteredResult = studentList.Where(s => s.Age > 12 && s.Age < 20);
output:
-------
John
Bill
Ron

IList mixedList = new ArrayList();


mixedList.Add(0);
mixedList.Add("One");
mixedList.Add("Two");
mixedList.Add(3);
mixedList.Add(new Student() { StudentID = 1, StudentName = "Bill" });

OfType:-
=======
var stringResult = mixedList.OfType<string>();
output:
-------
One
Two

Sorting Operators: OrderBy & OrderByDescending &ThenBy & ThenByDescending:


--------------------------------------------------------------------------
OrderBy:-
========
var studentsInAscOrder = studentList.OrderBy(s => s.StudentName);
output:
-------
Bill
John
Ram
Ron
Steve

OrderByDescending:-
==================
var studentsInDescOrder = studentList.OrderByDescending(s => s.StudentName);
output:
-------
Steve
Ron
Ram
John
Bill

ThenBy:-
=======
var thenByResult = studentList.OrderBy(s => s.StudentName).ThenBy(s => s.Age);
output:
-------
StudentName: Bill, Age: 25
StudentName: John, Age: 18
StudentName: Ram, Age: 18
StudentName: Ram, Age: 20
StudentName: Ron, Age: 19
StudentName: Steve, Age: 15

ThenByDescending-
=================
var thenByDescResult = studentList.OrderBy(s => s.StudentName).ThenByDescending(s
=> s.Age);
output:
-------
StudentName: Bill, Age: 25
StudentName: John, Age: 18
StudentName: Ram, Age: 20
StudentName: Ram, Age: 18
StudentName: Ron, Age: 19
StudentName: Steve, Age: 15

Grouping Operators: GroupBy & ToLookup:-


---------------------------------------
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Abram" , Age = 21 }
};

GroupBy :-
=========
var groupedResult = studentList.GroupBy(s => s.Age);
foreach (var ageGroup in groupedResult)
{
Console.WriteLine("Age Group: {0}", ageGroup.Key); //Each group has a key

foreach(Student s in ageGroup) //Each group has a inner collection


Console.WriteLine("Student Name: {0}", s.StudentName);
}
output:
-------
AgeGroup: 18
StudentName: John
StudentName: Bill
AgeGroup: 21
StudentName: Steve
StudentName: Abram
AgeGroup: 20
StudentName: Ram

Joining Operator: Join:-


-----------------------
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", StandardID =1 },
new Student() { StudentID = 2, StudentName = "Moin", StandardID =1 },
new Student() { StudentID = 3, StudentName = "Bill", StandardID =2 },
new Student() { StudentID = 4, StudentName = "Ram" , StandardID =2 },
new Student() { StudentID = 5, StudentName = "Ron" }
};

IList<Standard> standardList = new List<Standard>() {


new Standard(){ StandardID = 1, StandardName="Standard 1"},
new Standard(){ StandardID = 2, StandardName="Standard 2"},
new Standard(){ StandardID = 3, StandardName="Standard 3"}
};

Join Query C#:


==============
var innerJoin = studentList.Join(// outer sequence
standardList, // inner sequence
student => student.StandardID, // outerKeySelector
standard => standard.StandardID, // innerKeySelector
(student, standard) => new // result selector
{
StudentName = student.StudentName,
StandardName = standard.StandardName
});
output:
-------
John - Standard 1
Moin - Standard 1
Bill - Standard 2
Ram - Standard 2

GroupJoin:-
===========
var groupJoin = standardList.GroupJoin(studentList, //inner sequence
std => std.StandardID, //outerKeySelector
s => s.StandardID, //innerKeySelector
(std, studentsGroup) => new // resultSelector
{
Students = studentsGroup,
StandarFulldName = std.StandardName
});

foreach (var item in groupJoin)


{
Console.WriteLine(item.StandarFulldName );

foreach(var stud in item.Students)


Console.WriteLine(stud.StudentName);
}
output:
-------
Standard 1:
John,
Moin,
Standard 2:
Bill,
Ram,
Standard 3:

Projection Operators: Select, SelectMany:-


-----------------------------------------
Select:-
========
The Select operator always returns an IEnumerable collection which contains
elements based on a transformation function. It is similar to the Select clause of
SQL that produces a flat result set.
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 21 }
};
var selectResult = studentList.Select(s => new { Name = s.StudentName ,
Age = s.Age });

Quantifier Operators:-
---------------------
The quantifier operators evaluate elements of the sequence on some condition and
return a boolean value to indicate that some or all elements satisfy the condition.

All:-
=====
The All operator evalutes each elements in the given collection on a specified
condition and returns True if all the elements satisfy a condition
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 }
};
// checks whether all the students are teenagers
bool areAllStudentsTeenAger = studentList.All(s => s.Age > 12 && s.Age < 20);
Output:
-------
false

Any:-
=====
Any checks whether any element satisfy given condition or not? In the following
example, Any operation is used to check whether any student is teen ager or not.
bool isAnyStudentTeenAger = studentList.Any(s => s.age > 12 && s.age < 20);
Output:
-------
true

Contains:-
==========
The Contains operator checks whether a specified element exists in the collection
or not and returns a boolean.
IList<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18 } ,
new Student() { StudentID = 2, StudentName = "Steve", Age = 15 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 25 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 } ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 }
};
Student std = new Student(){ StudentID =3, StudentName = "Bill"};
bool result = studentList.Contains(std); //returns false

As you can see in the above example, Contains returns false even if "Bill" exists
in the studentList. This is because the Contains extension method only compares
reference of an object but not the actual values of an object. So to compare values
of the student object, you need to create a class by implementing IEqualityComparer
interface, that compares values of two Student objects and returns boolean.

Aggregation Operator:
--------------------
Average:-
=========
Average extension method calculates the average of the numeric items in the
collection. Average method returns nullable or non-nullable decimal, double or
float value.
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};

var avgAge = studentList.Average(s => s.Age);


Console.WriteLine("Average Age of Student: {0}", avgAge);
Output:
-------
Average Age of Student: 17.4

Count:-
=======
The Count operator returns the number of elements in the collection or number of
elements that have satisfied the given condition.
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Mathew" , Age = 15 }
};

var numOfStudents = studentList.Count();


Console.WriteLine("Number of Students: {0}", numOfStudents);
Output:
-------
Number of Students: 5

Max:-
=====
The Max operator returns the largest numeric element from a collection.
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};
var oldest = studentList.Max(s => s.Age);
Console.WriteLine("Oldest Student Age: {0}", oldest);
Output:
-------
Oldest Student Ag: 21

Sum:-
=====
The Sum() method calculates the sum of numeric items in the collection.
IList<Student> studentList = new List<Student>>() {
new Student() { StudentID = 1, StudentName = "John", Age = 13} ,
new Student() { StudentID = 2, StudentName = "Moin", Age = 21 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 18 } ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 15 }
};

var sumOfAge = studentList.Sum(s => s.Age);


Console.WriteLine("Sum of all student's age: {0}", sumOfAge);
var numOfAdults = studentList.Sum(s => {

if(s.Age >= 18)


return 1;
else
return 0;
});
Console.WriteLine("Total Adult Students: {0}", numOfAdults);
Output:
-------
Total Age of Student: 87
Total Adult Students: 3

Element Operators:
------------------
The ElementAt()
===============
method returns an element from the specified index from a given collection. If the
specified index is out of the range of a collection then it will throw an Index out
of range exception. Please note that index is a zero based index.
The ElementAtOrDefault()
========================
method also returns an element from the specified index from a collaction and if
the specified index is out of range of a collection then it will return a default
value of the data type instead of throwing an error.

IList<int> intList = new List<int>() { 10, 21, 30, 45, 50, 87 };


IList<string> strList = new List<string>() { "One", "Two", null, "Four", "Five" };

Console.WriteLine("1st Element in intList: {0}", intList.ElementAt(0));


Console.WriteLine("1st Element in strList: {0}", strList.ElementAt(0));
Console.WriteLine("2nd Element in intList: {0}", intList.ElementAt(1));
Console.WriteLine("2nd Element in strList: {0}", strList.ElementAt(1));
Console.WriteLine("3rd Element in intList: {0}", intList.ElementAtOrDefault(2));
Console.WriteLine("3rd Element in strList: {0}", strList.ElementAtOrDefault(2));
Console.WriteLine("10th Element in intList: {0} - default int value",
intList.ElementAtOrDefault(9));
Console.WriteLine("10th Element in strList: {0} - default string value
(null)",strList.ElementAtOrDefault(9));
Console.WriteLine("intList.ElementAt(9) throws an exception: Index out of range");
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine(intList.ElementAt(9));

Output:
-------
1st Element in intList: 10
1st Element in strList: One
2nd Element in intList: 21
2nd Element in strList:
3rd Element in intList: 30
3rd Element in strList: Three
10th Element in intList: 0 - default int value
10th Element in strList: - default string value (null)
intList.ElementAt(9) throws an exception: Index out of range
-------------------------------------------------------------
Run-time exception: Index was out of range....

The First()
===========
method returns the first element of a collection, or the first element that
satisfies the specified condition using lambda expression or Func delegate. If a
given collection is empty or does not include any element that satisfied the
condition then it will throw InvalidOperation exception.

IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };


IList<string> strList = new List<string>() { null, "Two", "Three", "Four",
"Five" };
IList<string> emptyList = new List<string>();

Console.WriteLine("1st Element in intList: {0}", intList.First());


Console.WriteLine("1st Even Element in intList: {0}", intList.First(i => i % 2 ==
0));
Console.WriteLine("1st Element in strList: {0}", strList.First());
Console.WriteLine("emptyList.First() throws an InvalidOperationException");
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine(emptyList.First());

Output:
-------
1st Element in intList: 7
1st Even Element in intList: 10
1st Element in strList:
emptyList.First() throws an InvalidOperationException
-----------------------------------------------------
Run-time exception: Sequence contains no elements...

The FirstOrDefault()
====================
method does the same thing as First() method. The only difference is that it
returns default value of the data type of a collection if a collection is empty or
doesn't find any element that satisfies the condition.

IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };


IList<string> strList = new List<string>() { null, "Two", "Three", "Four",
"Five" };
IList<string> emptyList = new List<string>();

Console.WriteLine("1st Element in intList: {0}", intList.FirstOrDefault());


Console.WriteLine("1st Even Element in intList: {0}", intList.FirstOrDefault(i => i
% 2 == 0));
Console.WriteLine("1st Element in strList: {0}", strList.FirstOrDefault());
Console.WriteLine("1st Element in emptyList: {0}", emptyList.FirstOrDefault());

Output:
-------
1st Element in intList: 7
1st Even Element in intList: 10
1st Element in strList:
1st Element in emptyList:

The Last()
==========
method returns the last element from a collection, or the last element that
satisfies the specified condition using lambda expression or Func delegate. If a
given collection is empty or does not include any element that satisfied the
condition then it will throw InvalidOperation exception.

IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };


IList<string> strList = new List<string>() { null, "Two", "Three", "Four",
"Five" };
IList<string> emptyList = new List<string>();

Console.WriteLine("Last Element in intList: {0}", intList.Last());


Console.WriteLine("Last Even Element in intList: {0}", intList.Last(i => i % 2 ==
0));
Console.WriteLine("Last Element in strList: {0}", strList.Last());
Console.WriteLine("emptyList.Last() throws an InvalidOperationException");
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine(emptyList.Last());

Output:
-------
Last Element in intList: 87
Last Even Element in intList: 50
Last Element in strList: Five
emptyList.Last() throws an InvalidOperationException
----------------------------------------------------
Run-time exception: Sequence contains no elements...

The LastOrDefault()
===================
method does the same thing as Last() method. The only difference is that it returns
default value of the data type of a collection if a collection is empty or doesn't
find any element that satisfies the condition.

IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };


IList<string> strList = new List<string>() { null, "Two", "Three", "Four",
"Five" };
IList<string> emptyList = new List<string>();

Console.WriteLine("Last Element in intList: {0}", intList.LastOrDefault());


Console.WriteLine("Last Even Element in intList: {0}", intList.LastOrDefault(i => i
% 2 == 0));
Console.WriteLine("Last Element in strList: {0}", strList.LastOrDefault());
Console.WriteLine("Last Element in emptyList: {0}", emptyList.LastOrDefault());

Output:
-------
Last Element in intList: 7
Last Even Element in intList: 10
Last Element in strList:
Last Element in emptyList:

Single()
========
returns the only element from a collection, or the only element that satisfies the
specified condition. If a given collection includes no elements or more than one
elements then Single() throws InvalidOperationException.

The SingleOrDefault()
=====================
method does the same thing as Single() method. The only difference is that it
returns default value of the data type of a collection if a collection is empty or
includes more than one element or finds no element or more than one element for the
specified condition.

IList<int> oneElementList = new List<int>() { 7 };


IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four",
"Five" };
IList<string> emptyList = new List<string>();

Console.WriteLine("The only element in oneElementList: {0}",


oneElementList.Single());
Console.WriteLine("The only element in oneElementList:
{0}",oneElementList.SingleOrDefault());
Console.WriteLine("Element in emptyList: {0}", emptyList.SingleOrDefault());
Console.WriteLine("The only element which is less than 10 in intList:
{0}",intList.Single(i => i < 10));
//Followings throw an exception
//Console.WriteLine("The only Element in intList: {0}", intList.Single());
//Console.WriteLine("The only Element in intList: {0}", intList.SingleOrDefault());
//Console.WriteLine("The only Element in emptyList: {0}", emptyList.Single());

Output:
-------
The only element in oneElementList: 7
The only element in oneElementList: 7
Element in emptyList: 0
The only element which is less than 10 in intList: 7

Equality Operator:
------------------
SequenceEqual:
==============
There is only one equality operator: SequenceEqual. The SequenceEqual method checks
whether the number of elements, value of each element and order of elements in two
collections are equal or not.

If the collection contains elements of primitive data types then it compares the
values and number of elements, whereas collection with complex type elements,
checks the references of the objects. So, if the objects have the same reference
then they considered as equal otherwise they are considered not equal.

IList<string> strList1 = new List<string>(){"One", "Two", "Three", "Four",


"Three"};
IList<string> strList2 = new List<string>(){"One", "Two", "Three", "Four",
"Three"};

bool isEqual = strList1.SequenceEqual(strList2); // returns true


Console.WriteLine(isEqual);

Output:
-------
true

Concatenation Operator:
-----------------------
Concat:-
========
The Concat() method appends two sequences of the same type and returns a new
sequence (collection).

IList<string> collection1 = new List<string>() { "One", "Two", "Three" };


IList<string> collection2 = new List<string>() { "Five", "Six"};

var collection3 = collection1.Concat(collection2);


foreach (string str in collection3)
Console.WriteLine(str);

Output:
-------
One
Two
Three
Five
Six
===================================================================================
==================================

===================================================COMPLETED=======================
==================================
SQL:
====

Q) What is SQL?
SQL stands for Structured Query Language , and it is used to communicate with the
Database. This is a standard language used to perform tasks such as retrieval,
updation, insertion and deletion of data from a database.
===================================================================================
==================================
Q)What is a Database?
Database is nothing but an organized form of data for easy access, storing,
retrieval and managing of data. This is also known as structured form of data which
can be accessed in many ways.
===================================================================================
==================================
Q) What are the different type of SQL's statements ?
1. DDL � Data Definition Language
DDL is used to define the structure that holds the data. For example, Create,
Alter, Drop and Truncate table.

2. DML � Data Manipulation Language


DML is used for manipulation of the data itself. Typical operations are Insert,
Delete, Update and retrieving the data from the table. The Select statement is
considered as a limited version of the DML, since it can't change the data in the
database. But it can perform operations on data retrieved from the DBMS, before the
results are returned to the calling function.

3. DCL � Data Control Language


DCL is used to control the visibility of data like granting database access and set
privileges to create tables, etc. Example - Grant, Revoke access permission to the
user to access data in the database.
===================================================================================
==================================
Q)What is a key? A candidate key? A primary key? A alternate key? A foreign key?A
Natural key?
-> A Key is a set of one or more columns that is used to uniquely identify the
record in a table.
-> It is used to fetch records from table based on the condition/requirement.
-> Key provide several types of constraints like column can not store duplicate
values or null values.
-> Keys are also used to generate relationship among different tables or views.

Types of Keys:
--------------
Database supports the following types of keys.
1)Super Key
2)Minimal Super Key
3)Candidate Key
4)Primary Key
5)Unique Key
6)Alternate Key
7)Composite Key
8)Foreign Key
9)Natural Key
10)Surrogate Key

Primary Key:-
-------------
-> Primary key is a set of one or more columns of a table that uniquely identify a
record in database table.
-> It can not accept null and duplicate values. A table can have only one primary
key and one candidate key can select as a primary key.
-> The primary key should be choosen such that its attributes are never or rarely
changed.
-> By default, Primary key is clustered index, and the data in database table is
physically organized in the sequence of clustered index.
-> Primary key can be related to another tables as a Foreign Key.
-> We can generate ID automatically with the help of Auto Increment field. Primary
key supports Auto Increment value.
-> We can define Primary key constraint on temporary table and table variable.
-> We can't delete primary key value from the parent table which is used as a
foreign key in child table. To delete we first need to delete that primary key
value from the child table.

Candidate Key:-
---------------
-> Candidate Key is a set of one or more fields/columns of a table that uniquely
identify a record in database table.
-> We can create multiple Candidate Keys in one table, each Candidate Key can work
as Primary Key.

Alternate Key:-
---------------
-> Alternate keys are candidate keys that are not selected as primary key.
Alternate key can also work as a primary key.
-> Alternate key is also called �Secondary Key�.

Unique Key:-
------------
-> Uniquekey is a set of one or more fields/columns of a table that uniquely
identify a record in database table.
-> It is like Primary key but it can accept only one null value and it can not
accept duplicate values.
-> Unique Constraint doesn't supports Auto Increment value.

Foreign Key:-
-------------
-> Foreign Key is a field in database table that is Primary key in another table.
It can accept multiple null, duplicate values.
Example:-
---------
-> The "PersonID" column in the "Persons" table is the PRIMARY KEY in the "Persons"
table.
The "PersonID" column in the "Orders" table is a FOREIGN KEY in the "Orders"
table.
Uses:-
------
=>The FOREIGN KEY constraint is used to prevent actions that would destroy links
between tables.
=>The FOREIGN KEY constraint also prevents invalid data from being inserted into
the foreign key column, because it has to be one of the values contained in the
table it points to.

Natural Keys:-
--------------
-> A natural key is a key composed of columns that actually have a logical
relationship to other columns within a table.
-> For example, if we use Student_Id, Student_Name and Father_Name columns to form
a key then it would be �Natural Key� because there is definitely a relationship
between these columns and other columns that exist in table.
-> Natural keys are often called �Business Key � or �Domain Key�.

Surrogate Key:-
---------------
-> Surrogate key is an artificial key that is used to uniquely identify the record
in table.
-> For example, in SQL Server or Sybase database system contain an artificial key
that is known as �Identity�. Surrogate keys are just simple sequential number.
-> Surrogate keys are only used to act as a primary key.
Example:
--------
Branch_Id is a Surrogate Key in Branch_Info table and Student_Id is a Surrogate key
of Student_Information table.

Sample Example:-
----------------
--Department Table
CREATE TABLE Department
(
DeptID int PRIMARY KEY, --primary key
Name varchar (50) NOT NULL,
Address varchar (200) NOT NULL
)
--Student Table
CREATE TABLE Student
(
ID int PRIMARY KEY, --primary key
RollNo varchar(10) NOT NULL,
Name varchar(50) NOT NULL,
EnrollNo varchar(50) UNIQUE, --unique key
Address varchar(200) NOT NULL,
DeptID int FOREIGN KEY REFERENCES Department(DeptID) --foreign key
)
===================================================================================
==================================
Q) Difference between Primary Key and Unique Key?
Primary Key:-
-------------
->Primary Key can't accept null values and duplicate values.
->By default, Primary key is clustered index and data in the database table is
physically organized in the sequence of clustered index.
->We can have only one Primary key in a table.
->Primary key can be made foreign key into another table.

Unique Key:-
------------
->Unique key can accept only one null value and can not accept duplicate values.
->By default, Unique key is a non-clustered index.
->We can have more than one unique key in a table.
->Unique key can be made foreign key into another table.
===================================================================================
==================================
Q) Difference between Primary Key and Foreign Key?
Primary Key:-
-------------
->Primary key uniquely identify a record in the table.
->Primary Key can't accept null values.
->By default, Primary key is clustered index and data in the database table is
physically organized in the sequence of clustered index.
->We can have only one Primary key in a table.

Foreign Key:-
-------------
->Foreign key is a field in the table that is primary key in another table.
->Foreign key can accept null value.
->Foreign key do not automatically create an index, clustered or non-clustered. You
can manually create an index on foreign key.
->We can have more than one foreign key in a table.
===================================================================================
==================================
Q) How can you create an empty table from an existing table?
Select * Into <DestinationTableName> From <SourceTableName> Where 1 = 2

Note:-
------
This will not copy indexes, keys, etc.
1=2 will prevent data copying from source to destination table.
===================================================================================
==================================
Q)What is Index?
->Index is a database object, which can be created on one or more columns (max 16
columns).
->creating the index will read the column(s) and forms a relevant data structure to
minimize the number of data comparisons.
->index will improve the performance of data retrieval and adds some overhead on
data modification such as create, delete and modify.
->A table can have only one clustered index, but a table can have multiple non-
clustered indexes.

Syntax to Create SQL Index in table:-


-------------------------------------
CREATE INDEX INDEX_NAME ON TABLE_NAME (COLUMN_NAME)+

Example to create Index on table:-


---------------------------------
CREATE INDEX SampleIndex ON UserInformation (UserName)

If you want to create an index on a combination of columns, you can list the column
names within the parentheses, separated by commas:
Example of creating SQL Index on multiple columns:-
---------------------------------------------------
CREATE INDEX SampleIndex ON UserInformation (UserName,FirstName)

To Drop Index on table use the below statement:-


----------------------------------------------
DROP INDEX TABLE_NAME.INDEX_NAME

SQL Server essentially supports two types of tables:


----------------------------------------------------
a clustered table, that is, one on which a clustered index has been defined, and a
heap table, or just plain heap. Unlike a clustered table, data within a heap is not
ordered in any way. It is essentially a pile of data.

Clustered Index:-
-----------------
A clustered index alters the way that the rows are stored. When you create a
clustered index on a column, SQL server sorts the table�s rows by that column(s).
It is like a dictionary, where all words are sorted in alphabetical order in the
entire book.

All table data is stored in 8 KB data pages. When a table contains a clustered
index, the clustered index tells SQL Server how to order the table�s data pages. It
does this by organizing those data pages into a B-tree structure,
RootNode
EmployeeId
Level 2 (Clustering Key)
1 to 10,00000

EmployeeId
EmployeeId
Level 1 (Clustering Key) Intermediate Level
(Clustering Key)
1 to 5,00000
1 to 5,00000
Level 0 EmployeeDetails EmployeeDetails Leaf Level Employee
Details Employee Details
for for For
For
Employee Id Employee Id EmployeeId
EmployeeId
1 to 2000 2000 to 4000 ....... 5,00000 to
5,20000 5,20000 to 5,4000

Fig: A b-tree index for a 1-million row table

The pages in Level 1 and Level 2, highlighted in both level1 & level2, are index
pages. In Level 1, each page contains information for 500,000 records. As
discussed, each of these pages stores not half a million rows, but rather half a
million clustered index values, plus a pointer down into the associated page on the
next level. For example, to retrieve the details for Employee 500, SQL Server would
read three pages: the root page in Level 2, the intermediate page in Level 1, and
the appropriate leaf level page in Level 0. The root page tells SQL Server which
intermediate level page to read, and the intermediate page tells it which specific
leaf level page to read.

Sample Example:-
----------------
SELECT CustomerID ,OrderDate ,SalesOrderNumber FROM Sales.SalesOrderHeader
WHERE SalesOrderID = 44242 ;

This table has a clustered index on the SalesOrderID column and SQL Server is able
to use it to navigate down through the clustered index B-tree to get the
information that is requested. If we were to visualize this operation, it would
look something like this:

Root Node SalesOrderID PageID


59391 750
59392 751

Intermediate level SalesOrderID PageID


(Page 750) 44150 814
44197 815
44244 816
44290 817
44333 818

Leaf level SalesOrderID OrderDate SalesOrderNumber


AccountNumber CustomerID
(Page 815) 44240 9/23/2005 SO44240 10-4030-
013580 13580
44241 9/23/2005 SO44241 10-4030-
028155 28155
44242 9/23/2005 SO44242 10-4030-
028163 28163

In the root node, the first entry points to PageID 750, for any values with a
SalesOrderID between NULL and 59391. The data we�re looking for, with a
SalesOrderID of 44242, falls within that range, so we navigate down to page 750, in
the intermediate level. Page 750 contains more granular data than the root node and
indicates that the PageID 815 contains SalesOrderID values between 44197 and 44243.
We navigate down to that page in the leaf level and, finally, upon loading PageID
815, we find all of our data for SalesOrderID 44242.

Non Clustered Index:-


---------------------
A non-clustered index, does not alter the way the rows are stored in the table. It
creates a completely different object within the table that contains the column(s)
selected for indexing and a pointer back to the table�s rows containing the data.
It is like an index in the last pages of a book, where keywords are sorted and
contain the page number to the material of the book for faster reference.

A non-clustered index on the computer_id column, in the previous example, would


look like the table below:

CREATE NONCLUSTERED INDEX [IX_NONCLUSTERED_COMPUTER_ID]


ON [dbo].[nics] ([computer_id] ASC)

Logical Representation of Non Clustered index:-


-----------------------------------------------
In a simple word , a non clustered index is a subset of a table. When we define a
non clustered index, SQL server store the set of non clustered key in a different
pages.Let us consider a table with four columns
(PersonId(PK),PersonType,FirstName,LastName) and a non clustered index on that
table.The actual table is stored in the order of personid column (Cluster index
key).In the below figure will give you a pictorial representation of non clustered
index. The non clustered index key column are stored apart from the actual
table.If you look into the Non clustered index ,you can notice that, records are
stored in the order of Firstname and lastname (Non Clustered index key) not as in
the order of actual table.To understand easily , non clustered index can be
considered as subset table of actual one.
Example:-
---------
Actual Table Non Cluster Index
-------------
------------------
PersonId PersonType FirstName LastName FirstName
LastName PersonId
1 EM Ken Sanchez Daine
Margheim 8
2 EM Terri Duffy Daine
Margheim 8
3 EM Roberto Sanchez Daine
Margheim 8
4 EM Rob Sanchez Daine
Margheim 8
5 EM Gail Sanchez Daine
Margheim 8
6 EM Jossef Sanchez Daine
Margheim 8
7 EM Dylan Sanchez Daine
Margheim 8
8 EM Gigi Sanchez Daine
Margheim 8
9 EM Michel Sanchez Daine
Margheim 8
10 EM Ovldliu Sanchez Daine
Margheim 8
11 EM Thierry Sanchez Daine
Margheim 8
12 EM Janice Sanchez Daine
Margheim 8
13 EM Michel Sanchez Daine
Margheim 8
14 EM Sharon Sanchez Daine
Margheim 8
15

>Now let us assume that we have a task to find out all records whose first name is
'Michael'.If you tried to find out from the Actual table , we need to go through
each record from top to bottom to check whether first name matches with our search
string 'Michael' as the records are not ordered based on the firstname column. It
will be more tedious task if we have thousands of records in that table. The task
will be much easier if we look into the the Non Clustered index side as the first
name and last name are alphabetically ordered.We can easily locate the records
which has firstname as 'Michael' and we do not need go beyond that as we are sure
that there will not be any more records with firstname as 'Michael'.
->Now, once we locate the records , we can go back to the Actual Table using the
PersonId (Cluster index key) to find the values of other columns and this operation
is called bookmark lookups or RID lookup.
->A non-clustered index contains a pointer back to the rowID (RID), of the table,
in order to relate the index�s column with the rest of the columns in a row.
->If a clustered index already exists in the table, the non-clustered index uses
the clustered index�s key as the row locator, instead of the RID reference.

Unique Index:-
--------------
->A unique index ensures that the index key contains no duplicate values and
therefore every row in the table or view is in some way unique.
->Both clustered and nonclustered indexes can be unique.

Index Benefits and Side Effects:-


--------------------------------
Benefits:-
----------
->A table without a clustered-index is called a �heap table�. A heap table has not
its data sorted. The SQL server has to scan the entire table in order to locate the
data, in a process called a �scan�.
In the case of a clustered index, the data are sorted on the key values (columns)
of the index. The SQL server is now able to locate the data by navigating down from
the root node, to the branch and finally to the leaf nodes of the B-tree structure
of the index. This process called a �seek�. The later approach is much faster, when
you want to filter or sort the data you want to retrieve.
->A non-clustered index, on the other hand, is a completely different object in the
table. It contains only a subset of the columns. It also contains a row locator
looking back to the table�s rows, or to the clustered index�s key.

Side Effects:-
--------------
->The side effects of indexes are related to the cost of INSERT, UPDATE, MERGE and
DELETE statements. Such statements can take longer to execute, in the presence of
indexes, as it alters the data in the table, thus to the indexes too.
->Imagine the situation of an INSERT statement. It has to add new rows in a table
with a clustered index. In such case the table rows may need to be re-positioned!
Remember�? The clustered index needs to order the data pages themselves! This will
cause overhead.

Differences between Clustered Index and NonClustered Index:-


------------------------------------------------------------
Clustered Index:-
-----------------
->A Table can have ONLY 1 Clustered Index.
->A Clustered Index always has Index Id of 0.
->A Primary Key constraint creates a Clustered Index by default.
->A Primary Key constraint can also be enforced by Nonclustered Index, You can
specify the index type while creating Primary Key.
->If the table does not have Clustered Index it is referred to as a "Heap".
->The leaf node of a Clustered Index contains data pages of the table on which it
is created.
->Clustered Index enforces a logical order on the rows. Rows are ordered based on
Clustering Key.

Nonclustered Index:-
--------------------
->Prior to SQL Server 2008 only 249 Nonclustered Indexes can be created. With SQL
Server 2008 and above 999 Nonclustered Indexes can be created.
->Nonclustered Indexes have Index Id > 0.
->A Unique Key constraint created a Nonclustered Index by default.
->A Unique Key constraint can also be enforced by Clustered Index, You can specify
the index type while creating Unique Key
->Nonclustered Index does not order actual data, It only orders columns present in
the Nonclustered Index based onIndex Key specified at the time of creation of
Nonclustered Index.
->A table may not have any Nonclustered Indexes.
->The leaf nodes of a Nonclustered Index consists of Index pages which contain
Clustering Key or RID to locate Data Row.
->When Clustered Index is not present leaf node points to Physical Location of the
row this is referred to as RID. When a Clustered Index is present this points to
Clustering Key (Key column on which Clustered Index is created).
===================================================================================
==================================
Q)What are the data types available and when to use which ones?
Exact Numeric Data Types:-
--------------------------
DATA TYPE FROM TO
bigint -9,223,372,036,854,775,808 9,223,372,036,854,775,807
int -2,147,483,648 2,147,483,647
smallint -32,768 32,767
tinyint 0 255
bit 0 1
decimal -10^38 +1 10^38 -1
numeric -10^38 +1 10^38 -1
money -922,337,203,685,477.5808 +922,337,203,685,477.5807
smallmoney -214,748.3648 +214,748.3647

Approximate Numeric Data Types:-


--------------------------------
DATA TYPE FROM TO
float -1.79E + 308 1.79E + 308
real -3.40E + 38 3.40E + 38

Date and Time Data Types:-


--------------------------
DATA TYPE FROM TO
datetime Jan 1, 1753 Dec 31, 9999
smalldatetime Jan 1, 1900 Jun 6, 2079
date Stores a date like June 30, 1991
time Stores a time of day like 12:30 P.M.
Note - Here, datetime has 3.33 milliseconds accuracy where as smalldatetime has 1
minute accuracy.

Character Strings Data Types:-


------------------------------
DATA TYPE Description
char Maximum length of 8,000 characters.( Fixed length non-Unicode
characters)
varchar Maximum of 8,000 characters.(Variable-length non-Unicode
data).
varchar(max) Maximum length of 231characters, Variable-length non-
Unicode data (SQL Server 2005 only).
text Variable-length non-Unicode data with a maximum length of
2,147,483,647 characters.

Unicode Character Strings Data Types:-


--------------------------------------
DATA TYPE Description
nchar Maximum length of 4,000 characters.( Fixed length Unicode)
nvarchar Maximum length of 4,000 characters.(Variable length Unicode)
nvarchar(max) Maximum length of 231characters (SQL Server 2005 only).( Variable
length Unicode)
ntext Maximum length of 1,073,741,823 characters. ( Variable length Unicode )

Binary Data Types:-


-------------------
DATA TYPE Description
binary Maximum length of 8,000 bytes(Fixed-length binary data )
varbinary Maximum length of 8,000 bytes.(Variable length binary data)
varbinary(max) Maximum length of 231 bytes (SQL Server 2005 only). ( Variable
length Binary data)
image Maximum length of 2,147,483,647 bytes. ( Variable length Binary Data)

Misc Data Types:-


------------------
DATA TYPE Description
sql_variant Stores values of various SQL Server-supported data types, except
text, ntext, and timestamp.
timestamp Stores a database-wide unique number that gets updated every time
a row gets updated
uniqueidentifier Stores a globally unique identifier (GUID)
xml Stores XML data. You can store xml instances in a column or a
variable (SQL Server 2005 only).
cursor Reference to a cursor object
table Stores a result set for later processing
===================================================================================
==================================
Q)Difference Between Char, Nchar, Varchar and Nvarchar Data Types in SQL Server?
->To store data as characters, numeric values and special characters in a database,
there are 4 data types that can be used.
->As you know we represent the character values within single quotes, for example
'Robin'. But do you know we can represent these same characters within double
quotes similar to programming languages representing a string, for example �Robin�?
This can be done by setting the value:

SET QUOTED_IDENTIFIER OFF

CHAR vs VARCHAR:-
-----------------
CHAR:-
------
It is a fixed length data type
Used to store non-Unicode characters
Occupiers 1 byte of space for each character

The bytes occupied by the variable are 20 even though the length of the characters
is 5. That means that irrespective of the character stored in the column, it will
occupy all bytes to store the value.

VARCHAR:-
---------
It is a variable length data type
Used to store non-Unicode characters
Occupies 1 byte of space for each character

DATALENGTH as 5 which means it will use only the number of bytes equal to the
number of characters. This will allow me to avoid wasting database space.

When to use what?


-----------------
If you are sure about the fixed length of the data that would be captured for any
specific column then go for CHAR data type and if the data may vary then go for
VARCHAR.

NCHAR vs NVARCHAR:-
-------------------
NCHAR :-
--------
Is a fixed length data type
Used to store Unicode characters (for example the languages Arabic, German and so
on)
Occupies 2 bytes of space for each character

The data length column shows 40 bytes even though the size declared is 20. It's
because NCHAR holds 2 bytes of space for each character.

NVARCHAR:-
----------
It is a variable-length data type
Used to store Unicode characters
Occupies 2 bytes of space for each character

DATALENGTH column is showing only 10 as a value. That is because it occupies 2


bytes of space for each character and the data length is only 5 characters,
therefore it will occupy 10 bytes of space in the database.

When to use what?


-----------------
If your column will store a fixed-length Unicode characters like French, Arabic and
so on characters then go for NCHAR. If the data stored in a column is Unicode and
can vary in length, then go for NVARCHAR.
Querying to NCHAR or NVARCHAR is a bit slower then CHAR or VARCHAR. So don't go for
NCHAR or NVARCHAR to store non-Unicode characters even though this data type
supports that.
===================================================================================
==================================
Q)What is Aggregate function in SQL?
->Aggregate functions helps to summarize the large volumes of data.
->This function can produced a single value for an entire group or table.
->They operate on sets of rows and return results based on groups of rows.

List of Aggregate Functions:-


----------------------------
->COUNT
->SUM
->AVERAGE
->MAX
->MIN

COUNT() function
-----------------
The SQL COUNT function returns the number of rows in a table satisfying the
criteria specified in the WHERE clause. It sets on the number of rows or non NULL
column values.
SQL Syntax : COUNT(*) , COUNT( [ALL|DISTINCT] expression )

Example : COUNT()
SELECT COUNT(*) FROM product_mast;

Example : Select count(*) from multiple tables


SELECT(SELECT COUNT(*) FROM employees) AS Total_Employees,(SELECT COUNT(*) FROM
departments)AS No_Of_Departments
FROM dual

Example : SQL count( ) with All


SELECT COUNT( ALL grade )
FROM customer;

Example : COUNT() with WHERE


SELECT COUNT(*) FROM product_mast WHERE rate>=20;

Example : COUNT() with DISTINCT


SELECT
COUNT(DISTINCT company)
FROM product_mast;

Example : COUNT() with GROUP BY


SELECT company, COUNT(*)
FROM product_mast GROUP BY company;

Example : COUNT() with HAVING


SELECT company, COUNT(*) FROM
product_mast GROUP BY company
HAVING COUNT(*)>2;

SUM() function
--------------
The SQL AGGREGATE SUM() function returns the sum of all selected column.
SQL Syntax : SUM ([ALL | DISTINCT] expression )

Example : SUM()
SELECT SUM(cost)
FROM product_mast;

Example : SQL sum() using multiple columns example


SELECT SUM (opening_amt + receive_amt)
FROM customer;

Example : SQL sum() with count()


SELECT cust_country, SUM(opening_amt),
COUNT(cust_country)
FROM customer
GROUP BY cust_country;

Example : SUM() with WHERE


SELECT SUM(cost)
FROM product_mast
WHERE qty>3;

Example : SUM() with GROUP BY


SELECT SUM(cost)
FROM product_mast
WHERE qty>3
GROUP BY
company;

Example : SUM() with HAVING


SELECT company, SUM(cost)
FROM product_mast
GROUP BY company
HAVING SUM(cost)>=170;

AVG() function
--------------
The SQL AVG function calculates the average value of a column of numeric type.
It returns the average of all non NULL values.
SQL Syntax : AVG ([ALL | DISTINCT] expression )

Example : AVG()
SELECT AVG(cost)
FROM product_mast;

Example : AVG() with HAVING


SELECT company, AVG(cost)
FROM product_mast
GROUP BY company
HAVING AVG(cost)>=65;

MAX() function
--------------
The aggregate function SQL MAX() is used to find the maximum value or highest value
of a certain column or expression. This function is useful to determine the largest
of all selected values of a column.
SQL Syntax : MAX ([ALL | DISTINCT] expression )

Example : MAX()
SELECT MAX(rate)
FROM product_mast;

Example : MAX() with HAVING


SELECT company, MAX(rate)
FROM product_mast
GROUP BY company
HAVING MAX(rate)=30;
MIN() function
--------------
The aggregate function SQL MIN() is used to find the minimum value or lowest value
of a column or expression. This function is useful to determine the smallest of all
selected values of a column.
Syntax : MIN([ALL | DISTINCT] expression )

Example : MIN()
SELECT MAX(rate)
FROM product_mast;

Example : MIN() with HAVING


SELECT company, MIN(rate)
FROM product_mast
GROUP BY company
HAVING MIN(rate)<20;
===================================================================================
==================================
Q)What's the difference between HAVING and WHERE?
WHERE:-
-------
->We can use WHERE clause with SELECT, INSERT, UPDATE and DELETE clause.
->WHERE clause is used for filtering rows and it applies on each and every row.
->WHERE clause is used before GROUP BY clause.
->We can't use aggregate functions in the where clause unless it is in a sub query
contained in a HAVING clause.

HAVING:-
--------
->HAVING clause can only be used with SELECT query. Means if you want perform
INSERT, UPDATE and DELETE clause it will retuns an error.
->HAVING clause is used to filter groups in SQL.
->HAVING clause is used after GROUP BY clause.
->We can use aggregate function in HAVING clause.
===================================================================================
==================================Q) Difference between TRUNCATE , DELETE and DROP
in SQL Server?
DELETE vs TRUNCATE:-
--------------------
1> TRUNCATE is a DDL command whereas DELETE is a DML command.
2> TRUNCATE is much faster than DELETE.
Reason: When you type DELETE.all the data get copied into the Rollback Tablespace
first.then delete operation get performed.Thatswhy when you type ROLLBACK after
deleting a table ,you can get back the data(The system get it for you from the
Rollback Tablespace).All this process take time.But when you type TRUNCATE,it
removes data directly without copying it into the Rollback Tablespace.Thatswhy
TRUNCATE is faster.Once you Truncate you cann't get back the data.
3> You cann't rollback in TRUNCATE but in DELETE you can rollback.TRUNCATE removes
the record permanently.
4> In case of TRUNCATE, trigger doesn't get fired. But in DML commands like DELETE,
trigger get fired.
5> You cann't use conditions(WHERE clause) in TRUNCATE, but in DELETE you can write
conditions using WHERE clause
6> TRUNCATE command resets the High Water Mark for the table but DELETE does not.
High Water Mark (HWM) represents total number of extent blocks used by a table.
The value of High Water Mark could sometime be more then the actual size
required/used by a table. This is because, some of these blocks of extents which at
one point of time had data but was later deleted would become empty.
DROP:-
------
->DROP is DDL command.
->The operation can not be rolled back.
->No DML triggers will be fired.
->The DROP command removes a table from the database.
->All the tables' rows, indexes and privileges will also be removed.
===================================================================================
==================================Q)Difference between Stored Procedure and
Function in SQL Server?
Stored Procedures are pre-compile objects which are compiled for first time and its
compiled format is saved, which executes (compiled code) whenever it is called. But
Function is compiled and executed every time when it is called.

User Defined Function


---------------------
->Function must return a value.
->Function allow only Select statements,it will not allow us to use DML statements.

->It will allow only input parameters, doesn't support output parameters.
->It will not allow us to use try-catch blocks.
->Transactions are not allowed within functions.
->We can use only table variables, it will not allow using temporary tables.
->It is not possible to call stored procedure inside user defined function .
->Functions can be called from a select statement.
->A UserDefinedFunction can be used in join clause as a result set.

Stored Procedure
----------------
->Stored Procedure may or not return values.
->Can have select statements as well as DML statements such as insert, update,
delete.
->It can have both input and output parameters.
->For exception handling we can use try catch blocks.
->Can use transactions within Stored Procedures.
->Can use both table variables as well as temporary table in it.
->Stored Procedures can call functions.
->Procedures can't be called from Select/Where/Having and so on statements.
Execute/Exec statement can be used to call/execute Stored Procedure.
->Procedures can't be used in Join clause
===================================================================================
==================================Q)Difference between Sql server 2005 and 2008?
SQL Server 2005
---------------
->XML datatype is introduced.
->Can not encrypt the entire database.
->Datetime is used for both date and time.
->No table datatype is included.
->SSIS is started using.
->Central Management Server(CMS) is not available.
->Policy based management(PBM) server is not available

Server 2008
-----------
->XML datatype is used.
->Can encrypt the entire database introduced in 2008.
->Date and time are seperately used for date and time
->Table datatype introduced.
->SSIS avails in this version.
->Central Management Server(CMS) is Introduced.
->Policy based management(PBM) server is Introduced.
===================================================================================
==================================Q)What is view in sql? What are the advantages
and disadvantages of views in sql server?
=>Views are virtual tables that are compiled at run time. The data associated with
views are not physically stored in the view, but it is stored in the base tables of
the view. A view can be made over one or more tables.
=>Generally we put those columns in view that we need to query again and again.
Once you have created the view, you can query view like as table. We can make
index, trigger on view.
->Views are stored in the database as an object so it doesn't require additional
storage space.

Types of views:-
----------------
There are the following two types of views:
->User-Defined Views
->System-Defined Views

User Defined Views are important so I describe only User Defined Views. They are of
two types:
-Simple View
-Complex view

Simple View:
------------
When a View is created on a single Table than it is called a Simple View. We can
apply all operations on a Simple View that we can apply on a table.

Complex view:
-------------
Views created on more than one table are called Complex View. We cannot perform all
operations of a table on a Complex View.
->It is not possible to do insert, update or delete in a complex view

Method 1: We can select all columns of a table. The following example demonstrates
that:
-----------------------------------------------------------------------------------
-----
Create View Employee_View1
as
select * from Employee_Details

Method 2: We can select specific columns of a table. The following example


demonstrates that:
-----------------------------------------------------------------------------------
----------
Create View Employee_View2
as
select Emp_Id,Emp_Name,Emp_City from Employee_Details

Method 3: We can select columns from a table with specific conditions. The
following example demonstrates that:
-----------------------------------------------------------------------------------
----------------------------
Create View Employee_View3
as
select * from Employee_Details where Emp_Id>3
Method 4: We can create a view that will hold the columns of different tables. The
following example demonstrates that:
-----------------------------------------------------------------------------------
-------------------------------
Create View Employee_View4
as
select
Employee_Details.Emp_Id,Employee_Details.Emp_Name,Employee_Details.Emp_Salary,Emplo
yee_Contact.MobileNo from Employee_Details
Left Outer Join
Employee_Contact
on
Employee_Details .Emp_Id= Employee_Contact.Emp_Id
Where Employee_Details.Emp_Id>2

Retrieve Data From View:


------------------------
->Select * from Employee_View4
->Select Emp_Id,Emp_Name,Emp_Salary from Employee_View4
The preceding query shows that we can select all the columns or some specific
columns from a view.

Dropping a View:
----------------
Drop View Employee_View1

Renaming the View:


------------------
Sp_Rename OldViewName , NewViewName

Getting Information about a view:


---------------------------------
Sp_Helptext Employee_View4

Altering a View:
----------------
Alter View Employee_View4
as
select
Employee_Details.Emp_Id,Employee_Details.Emp_Name,Employee_Details.Emp_Salary,Emplo
yee_Contact.MobileNo from Employee_Details
Left Outer Join
Employee_Contact
on
Employee_Details .Emp_Id= Employee_Contact.Emp_Id
Where Employee_Details.Emp_Id>5 and Employee_Details.Emp_City='Alwar'

Refreshing a View:
------------------
Exec sp_refreshview Employee_View1

SchemaBinding a VIEW :
----------------------
If we want to prevent any type of change in a base table then we can use the
concept of SCHEMABINDING. It will lock the tables being referred to by the view and
restrict all kinds of changes that may change the table schema (no Alter command).
->If we are using SchemaBinding then we can't use select statement.
Create View Employee_Details3
with SCHEMABINDING
as
select Emp_Id,Emp_Name,Emp_Salary,Emp_City from DBO.Employee_Details

Encrypt a view:
---------------
The �WITH ENCRYPTION� option can encrypt any views. That means it will not be
visible via SP_HELPTEXT. This option encrypts the definition. This option encrypts
the definition of the view. Users will not be able to see the definition of the
view after it is created. This is the main advantage of the view where we can make
it secure.

Create View Employee_Details4


with Encryption
as
select Emp_Id,Emp_Name,Emp_Salary,Emp_City from DBO.Employee_Details

Check Option:
--------------
The use of the Check Option in a view is to ensure that all the Update and Insert
commands must satisfy the condition in the view definition.

Create view [dbo].[Employee_Details7]


as
select * from Employee_Details
where Emp_Salary>30000
with Check Option
GO

DML Query In View:


------------------
In a view we can implement many types of DML query like insert, update and delete.
But for a successful implementation of a DML query we should use some conditions
like:
->View should not contain multiple tables
->View should not contain set function.
->View should not use the Distinct keyword
->View should not contain Group By, having clauses
->View should not contain Sub query
->View should not use Set Operators
->All NOT NULL columns from the base table must be included in the view in order
for the INSERT query to function.

Note:-
------
->We make views for security purpose since it restricts the user to view some
columns/fields of the table(s).
->One more advantage of Views is, data abstraction since the end user is not aware
of all the data present in database table
===================================================================================
==================================
Q)Difference Between Union and Union All in SQL Server?
UNION:-
-------
->UNION removes duplicate rows.
->UNION uses a distinct sort
->UNION cannot work with a column that has a TEXT data type.
UNION ALL:-
-----------
->�UNION ALL� does not remove the duplicate row. It returns all from all queries.
->�UNION ALL� does not use a distinct sort, so the performance of �UNION ALL� is
slightly higher than �UNION�.
->UNION ALL can work with all data type columns.

->OrderBy Clause should be used only on the last select statement in the union
query.

Note:-
------
For Union & UnionAll to work, the Number, DataType and Order of the Columns in the
select statements should be same.
===================================================================================
==================================
Q)How to Handle Null Values in SQL Server?
->SELECT ISNULL(col1, 0 ) FROM table1
->SELECT COALESCE(col1, 0 ) FROM table1
->select contactid,Title,FirstName,
MiddleName=(case MiddleName
when MiddleName is null then ..
when MiddleName = 'R' then ..
else 'No Name'
end), LastName
From Person.Contact
===================================================================================
==================================
Q)Case Expression in SQL Server with Example?
->Sometimes, you required to alter or modify the records based on some conditions
before return. In this case, you may use cursor or loop for modify your records. In
this situation Case expression is best alternative for Cursor/looping and also
provides better performance.
->You can use CASE expressions anywhere in the SQL Query like CASE expressions can
be used with in SELECT statement, WHERE clauses, Order by clause, HAVING
clauses,Insert, UPDATE and DLETE statements.
Syntax
------
CASE expression
WHEN expression1 THEN Result1
WHEN expression2 THEN Result2
ELSE ResultN
END

SELECT statement with CASE expressions


--------------------------------------
SELECT FirstName, State=(CASE StateCode
WHEN 'MP' THEN 'Madhya Pradesh'
WHEN 'UP' THEN 'Uttar Pradesh'
WHEN 'DL' THEN 'Delhi'
ELSE NULL
END), PayRate
FROM dbo.Customer

Update statement with CASE expression


--------------------------------------
UPDATE Customer
SET StateCode = CASE StateCode
WHEN 'MP' THEN 'Madhya Pradesh'
WHEN 'UP' THEN 'Uttar Pradesh'
WHEN 'DL' THEN 'Delhi'
ELSE NULL
END

ORDER BY clause with CASE expressions


-------------------------------------
SELECT * FROM dbo.Customer
ORDER BY
CASE Gender WHEN 'M' THEN FirstName END Desc,
CASE Gender WHEN 'F' THEN LastName END ASC

Having Clause with CASE expression


----------------------------------
SELECT FirstName ,StateCode,Gender, Total=MAX(PayRate)
FROM dbo.Customer
GROUP BY StateCode,Gender,FirstName
HAVING (MAX(CASE Gender WHEN 'M'
THEN PayRate
ELSE NULL END) > 180.00
OR MAX(CASE Gender WHEN 'F'
THEN PayRate
ELSE NULL END) > 170.00)
===================================================================================
==================================
Q)What is a trigger in SQL Server?What are the different types of triggers?
=>Triggers are special kind of stored procedure that can be executed automatically
when a DDL or DML statement associated with the trigger is executed. (OR) In other
ways, a trigger can be defined to execute before or after an INSERT, UPDATE, or
DELETE operation, either once per modified row, or once per SQL statement.
=>Triggers can be assigned to tables or views. However, although there are two
types of triggers, INSTEAD OF and AFTER, only one type of trigger can be assigned
to views. An INSTEAD OF trigger is the one that is usually associated with a view.

Note: It is not possible to create a trigger to fire when a data modification


occurs in two or more tables. A trigger can be associated only with a single table.

Why Use Triggers?


-----------------
=>To improve data integrity, trigger can be used. When an action is performed on
data, it is possible to check if the manipulation of the data concurs with the
underlying business rules, and thus avoids erroneous entries in a table. For
example:
------------
In a banking scenario, when a request is made to withdraw cash from a cash point,
the stored procedure will create a record on the client's statement table for the
withdrawal, and the trigger will automatically reduce the balance as required. The
trigger may also be the point at which a check is made on the client's balance to
verify that there is enough balance to allow the withdrawal. By having a trigger on
the statement table, we are secure in the knowledge that any statement entry made,
whether withdrawal or deposit, will be validated and processed in one central
place.

Types of DML Triggers:


----------------------
(1) After Trigger (using FOR/AFTER CLAUSE):
-------------------------------------------
This trigger fires after SQL Server completes the execution of the action
successfully that fired it.
->AFTER TRIGGERS can be classified further into three types as:
(1) AFTER INSERT Trigger.
(2) AFTER UPDATE Trigger.
(3) AFTER DELETE Trigger.

For Example :
If you insert record/row in a table then the trigger associated with the insert
event on this table will fire only after the row passes all the checks, such as
primary key, rules, and constraints. If the record/row insertion fails, SQL Server
will not fire the After Trigger.

Sample Query:-
-------------
-- Create trigger on table Employee_Demo for Insert statement
CREATE TRIGGER trgAfterInsert ON Employee_Demo
FOR INSERT |FOR UPDATE |FOR DELETE
AS
declare @empid int, @empname varchar(55), @empsal decimal(10,2), @audit_action
varchar(100);
select @empid=i.Emp_ID from inserted i;
select @empname=i.Emp_Name from inserted i;
select @empsal=i.Emp_Sal from inserted i;
set @audit_action='Inserted Record -- After Insert Trigger.';
insert into
Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@empid,@empname,@empsal,@audit_action,getdate());
PRINT 'AFTER INSERT trigger fired.'

(2) Instead of Trigger (using INSTEAD OF CLAUSE)


------------------------------------------------
This trigger fires before SQL Server starts the execution of the action that fired
it. This is much more different from the AFTER trigger, which fires after the
action that caused it to fire. We can have an INSTEAD OF insert/update/delete
trigger on a table that successfully executed but does not include the actual
insert/update/delet to the table.

->INSTEAD OF TRIGGERS can be classified further into three types as:


(1) INSTEAD OF INSERT Trigger.
(2) INSTEAD OF UPDATE Trigger.
(3) INSTEAD OF DELETE Trigger.

For Example :
If you insert record/row in a table then the trigger associated with the insert
event on this table will fire before the row passes all the checks, such as primary
key, rules, and constraints. If the record/row insertion fails, SQL Server will
fire the Instead of Trigger.

Sample Query:-
--------------
-- Create trigger on table Employee_Demo for Update statement
CREATE TRIGGER trgInsteadOfUpdate ON dbo.Employee_Demo
INSTEAD OF Insert |INSTEAD OF Update |INSTEAD OF DELETE
AS
declare @emp_id int, @emp_name varchar(55), @emp_sal decimal(10,2), @audit_action
varchar(100);
select @emp_id=i.Emp_ID from inserted i;
select @emp_name=i.Emp_Name from inserted i;
select @emp_sal=i.Emp_Sal from inserted i;
BEGIN
BEGIN TRAN
if(@emp_sal>=1000)
begin
RAISERROR('Cannot Insert where salary < 1000',16,1); ROLLBACK; end
else begin
insert into
Employee_Demo_Audit(Emp_ID,Emp_Name,Emp_Sal,Audit_Action,Audit_Timestamp)
values(@emp_id,@emp_name,@emp_sal,@audit_action,getdate());
COMMIT;
PRINT 'Record Updated -- Instead Of Update Trigger.'; END
--Output will be

Advantages of trigger:
----------------------
1) Triggers can be used as an alternative method for implementing referential
integrity constraints.
2) By using triggers, business rules and transactions are easy to store in database
and can be used consistently even if there are future updates to the database.
3) It controls on which updates are allowed in a database.
4) When a change happens in a database a trigger can adjust the change to the
entire database.
5) Triggers are used for calling stored procedures.

Disadvantages of trigger:
-------------------------
1) Programmers don�t have full control: Since business rules are hidden,
programmers don�t have full control over the database. BY this, a program can
generate several actions.
2) Increase in complexity: Triggers increase the complexity of a database as they
have hard coded rules already implemented.
3) Decrease in performance of the database: By the complex nature of the database
programs take more time to execute and there can be hidden performance downtimes.
===================================================================================
==================================
Q)How to execute stored procedure in sql server with parameters?
EXEC GetTaskEvents @TaskName = 'TESTTASK', @ID = 2;
===================================================================================
==================================
Q)Difference between CTE and Temp Table and Table Variable?
Temp Table or Table variable or CTE are commonly used for storing data temporarily
in SQL Server.

CTE (Common Table Expression):-


-------------------------------
The common table expression (CTE) is a temporary named result set that you can
reference within a SELECT, INSERT, UPDATE, or DELETE statement.
CTE improves readability and ease in maintenance of complex queries and sub-
queries.

SQL Server supports two types of CTEs-recursive and nonrecursive.

Disadvantages:-
--------------
For example, a stored proc with two update statements that could use the same CTE.
But the 'scope' of the CTE is the first query only.

A sub query without CTE is given below :


----------------------------------------
SELECT * FROM (
SELECT Addr.Address, Emp.Name, Emp.Age From Address Addr
Inner join Employee Emp on Emp.EID = Addr.EID) Temp
WHERE Temp.Age > 50
ORDER BY Temp.NAME

By using CTE above query can be re-written as follows :


-------------------------------------------------------
With CTE1(Address, Name, Age)--Column names for CTE, which are optional
AS
(
SELECT Addr.Address, Emp.Name, Emp.Age from Address Addr
INNER JOIN EMP Emp ON Emp.EID = Addr.EID
)
SELECT * FROM CTE1 --Using CTE
WHERE CTE1.Age > 50
ORDER BY CTE1.NAME

When to use CTE:


----------------
This is used to store result of a complex sub query for further use.
This is also used to create a recursive query.

Temporary Tables:-
-----------------
-> Temporary Tables, are similar to the permanent tables. Permanent tables get
created in the database you specify, and remains in the database permanently,
untill you delete or drop them. Temporary tables are created inside Tempdb and are
automatically deleted, when they are no longer used.
-> In SQL Server, temporary tables are created at run-time and you can do all the
operations which you can do on a normal table.
-> Based on the scope and behavior temporary tables are of two types as given
below-

(1) Local Temp Table:-


----------------------
Local temp tables are only available to the SQL Server session or connection (means
single user) that created the tables. These are automatically deleted when the
session that created the tables has been closed. Local temporary table name is
stared with single hash ("#") sign.

CREATE TABLE #LocalTemp


(
UserID int,
Name varchar(50),
Address varchar(150)
)
The scope of Local temp table exist to the current session of current user means to
the current query window. If you will close the current query window or open a new
query window and will try to find above created temp table, it will give you the
error.

(2) Global Temp Table:-


----------------------
Global temp tables are available to all SQL Server sessions or connections (means
all the user). These can be created by any SQL Server connection user and these are
automatically deleted when all the SQL Server connections have been closed. Global
temporary table name is stared with double hash ("##") sign.
CREATE TABLE ##GlobalTemp
(
UserID int,
Name varchar(50),
Address varchar(150)
)
GO
Global temporary tables are visible to all SQL Server connections while Local
temporary tables are visible to only current SQL Server connection.

When to Use Temporary Tables?


------------------------------
->When we are doing large number of row manipulation in stored procedures.
->This is useful to replace the cursor. We can store the result set data into a
temp table, then we can manipulate the data from there.
->When we are having a complex join operation.

Points to Remember Before Using Temporary Tables-


-------------------------------------------------
->Temporary table created on tempdb of SQL Server. This is a separate database. So,
this is an additional overhead and can causes performance issues.
->Number of rows and columns need to be as minimum as needed.
->Tables need to be deleted when they are done with their work.

Table Variable:-
----------------
Table Variable acts like a variable and exists for a particular batch of query
execution. It gets dropped once it comes out of batch. This is also created in the
Tempdb database but not in the memory. This also allows you to create primary key,
identity at the time of Table variable declaration but not non-clustered index.

GO
DECLARE @TProduct TABLE
(
SNo INT IDENTITY(1,1),
ProductID INT,
Qty INT
)
--Insert data to Table variable @Product
INSERT INTO @TProduct(ProductID,Qty)
SELECT DISTINCT ProductID, Qty FROM ProductsSales ORDER BY ProductID ASC

--Select data
Select * from @TProduct

--Next batch
GO
Select * from @TProduct --gives error in next batch

When to Use Table Variable Over Temp Table:-


--------------------------------------------
Tablevariable is always useful for less data. If the result set returns a large
number of records, we need to go for temp table.

Note:-
------
->Temp Tables are physically created in the Tempdb database. These tables act as
the normal table and also can have constraints, index like normal tables.
->CTE is a named temporary result set which is used to manipulate the complex sub-
queries data. This exists for the scope of statement. This is created in memory
rather than Tempdb database. You cannot create any index on CTE.
->Table Variable acts like a variable and exists for a particular batch of query
execution. It gets dropped once it comes out of batch. This is also created in the
Tempdb database but not the memory.
===================================================================================
==================================
Q)How to insert values to identity column in SQL Server?
Allow insert into identity field:-
----------------------------------
You can alllow insert to the identity field by setting IDENTITY_INSERT ON for a
particular table as shown:

Insert Value to Identity field:-


--------------------------------
Now, lets see how to insert our own values to identity field ID with in the
Customer table.
SET IDENTITY_INSERT Customer ON
INSERT INTO Customer(ID,Name,Address) VALUES(3,'Rahul','Noida')
INSERT INTO Customer(ID,Name,Address) VALUES(4,'Rahul','Noida')
SET IDENTITY_INSERT Customer OFF
INSERT INTO Customer(Name,Address) VALUES('Rita','Noida')

Reseed the Identity field:-


---------------------------
DBCC checkident (Customer, RESEED, 0)
===================================================================================
==================================
Q)How to improve SQL Server database design and performance?
->Choose Appropriate Data Type
->Avoid nchar and nvarchar
->Avoid * in SELECT statement
->Use EXISTS instead of IN
->Avoid Having Clause
->Create Clustered and Non-Clustered Indexes
->Keep clustered index small
->Avoid Cursors
->Use Table variable inplace of Temp table
->Use UNION ALL inplace of UNION
->Use Schema name before SQL objects name
->Keep Transaction small
->SET NOCOUNT ON--Practice to set NOCOUNT ON since SQL Server returns number of
rows effected by SELECT,INSERT,UPDATE and DELETE statement. We can stop this by
setting NOCOUNT ON like as:
->Use TRY-Catch
->Use Stored Procedure for frequently used data and more complex queries
->Avoid prefix "sp_" with user defined stored procedure name
===================================================================================
==================================
Q)Definition and Use of Group by and Having Clause?
Group By Clause:-
-----------------
Group By clause is used for grouping the records of the database table(s).This
clause creates a single row for each group and this process is called aggregation.
To use group by clause we have to use at least one aggregate function in Select
statement. We can use group by clause without where clause.

SELECT Col1, Col2, Aggreate_function


FROM Table_Name
WHERE Condition
GROUP BY Col1, Col2

Having Clause:-
--------------
This clause operates only on group rows of table(s) and act as a filter like as
where clause. We use having clause to filter data that we get from group by clause.
To use having clause we need to use group by clause first.

-- Having clause without where condition


SELECT st_Name, SUM(st_Marks) AS 'Students Scored > 205'
FROM StudentMarks
GROUP BY st_Name
HAVING SUM(st_Marks) > 205

Note:-
------
->To use Group By Clause, we need to use at least one aggregate function
->All columns that are not used by aggregate function(s) must be in the Group By
list
->We can use Group By Clause with or without Where Clause.
->To use Having Clause, we have to use Group By Clause since it filters data that
we get from Group By Clause
===================================================================================
==================================
Q)SQL Integrity Constraints or Constraints?
Constraints are some rules that enforce on the data to be enter into the database
table. Basically constraints are used to restrict the type of data that can insert
into a database table.
Constraints can be defined in two ways:

Column Level:-
-------------
The constraints can be specified immediately after the column definition with the
CREATE TABLE statement. This is called column-level constraints.

Table Level:-
------------
The constraints can be specified after all the columns are defined with the ALTER
TABLE statement. This is called table-level constraints.

Types of SQL Constraints:-


--------------------------
In Microsoft SQL Server we have six types of constraints

Primary Key Constraints


-----------------------
Primary key is a set of one or more fields/columns of a table that uniquely
identify each record/row in database table. It can not accept null and duplicate
values.

Primary key constraint at column level


CREATE TABLE table_name
(
col1 datatype [CONSTRAINT constraint_name] PRIMARY KEY,
col2 datatype
);

Primary key constraint at table level


ALTER TABLE table_name
ADD[CONSTRAINT constraint_name] PRIMARY KEY (col1,col2)

Unique Key Constraints


----------------------
Unique key is a set of one or more fields/columns of a table that uniquely identify
each record/row in database table.It is like Primary key but it can accept only one
null value and it can not have duplicate values

Unique key constraint at column level


CREATE TABLE table_name
(
col1 datatype [CONSTRAINT constraint_name] UNIQUE,
col2 datatype
);

Unique key constraint at table level


ALTER TABLE table_name
ADD[CONSTRAINT constraint_name] UNIQUE (col1,col2)

Foreign Key Constraints


-----------------------
Foreign Key is a field in database table that is Primary key in another table. It
can accept multiple null and duplicate values.

Foreign key constraint at column level


CREATE TABLE table_name
(
col1 datatype [CONSTRAINT constraint_name] REFERENCES
referenced_table_name(referenced_table_column_name),
col2 datatype
);

Foreign key constraint at table level


ALTER TABLE table_name
ADD[CONSTRAINT constraint_name] REFERENCES
referenced_table_name(referenced_table_col)

Not Null Constraints


---------------------
This constraint ensures that all rows in the database table must contain value for
the column which is specified as not null means a null value is not allowed in that
column.

Not Null constraint at column level


CREATE TABLE table_name
(
col1 datatype [CONSTRAINT constraint_name] NOT NULL,
col2 datatype
);

Not Null constraint at table level


ALTER TABLE table_name
ALTER COLUMN col1 datatype NOT NULL

Check Constraints
-----------------
This constraint defines a business rule on a column in the database table that each
row of the table must follow this rule.
Check constraint at column level
CREATE TABLE table_name
(
col1 datatype [CONSTRAINT constraint_name] CHECK (condition),
col2 datatype
);

Check constraint at table level


ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK(condition)
===================================================================================
==================================
Q)Different Types of SQL Server Functions?
-> Function is a database object in Sql Server. Basically it is a set of sql
statements that accepts only input parameters, perform actions and return the
result.
-> Function can return only single value or a table.
-> We can�t use function to Insert, Update, Delete records in the database
table(s).

Types of Function:-
--------------------
1) System Defined Function:-
----------------------------
These functions are defined by Sql Server for different purpose. We have two types
of system defined function in Sql Server
a) Scalar Function:
-------------------
Scalar functions operates on a single value and returns a single value. Below is
the list of some useful Sql Server Scalar functions.

Scalar Function Description


-----------------------------------------------------------------------------------
--------------
abs(-10.67) This returns absolute number of the given number means
10.67.
rand(10) This will generate random number of 10 characters.
round(17.56719,3) This will round off the given number to 3 places of decimal
means 17.567
upper('dotnet') This will returns upper case of given string means
'DOTNET'
lower('DOTNET') This will returns lower case of given string means
'dotnet'
ltrim(' dotnet') This will remove the spaces from left hand side of 'dotnet'
string.
convert(int, 15.56) This will convert the given float value to integer
means 15.

b) Aggregate Function:
----------------------
Aggregate functions operates on a collection of values and returns a single value.
Below is the list of some useful Sql Server Aggregate functions.

Aggregate Function Description


-------------------------------------------------------------------------------
max() This returns maximum value from a collection of values.
min() This returns minimum value from a collection of values.
avg() This returns average of all values in a collection.
count() This returns no of counts from a collection of values.
2) User Defined Function:-
--------------------------
These functions are created by user in system database or in user defined database.
We have three types of user defined functions.

a) Scalar Function
------------------
User defined scalar function also returns single value as a result of actions
perform by function. We return any datatype value from function.

--Create function to get emp full name


Create function fnGetEmpFullName
(
@FirstName varchar(50),
@LastName varchar(50)
)
returns varchar(101)
AS
Begin return (Select @FirstName + ' '+ @LastName);
END

--Calling the above created function


Select dbo.fnGetEmpFullName(FirstName,LastName) as Name, Salary from Employee

b) Inline Table-Valued Function:


--------------------------------
User defined inline table-valued function returns a table variable as a result of
actions perform by function. The value of table variable should be derived from a
single SELECT statement.

--Create function to get employees


Create function fnGetEmployee()
returns Table
AS
Begin return (Select * from Employee)
END

--Now call the above created function


Select * from fnGetEmployee()

c) Multi-Statement Table-Valued Function:


------------------------------------------
User defined multi-statement table-valued function returns a table variable as a
result of actions perform by function. In this a table variable must be explicitly
declared and defined whose value can be derived from a multiple sql statements.

--Create function for EmpID,FirstName and Salary of Employee


Create function fnGetMulEmployee()
returns @Emp Table
(
EmpID int,
FirstName varchar(50),
Salary int
)
As
begin
Insert into @Emp Select e.EmpID,e.FirstName,e.Salary from Employee e;
--Now update salary of first employee
update @Emp set Salary=25000 where EmpID=1;
--It will update only in @Emp table not in Original Employee table
return
end

--Now call the above created function


Select * from fnGetMulEmployee()

--Now see the original table. This is not affected by above function update command
Select * from Employee

KeyPoints:-
-----------
->Unlike Stored Procedure, Function returns only single value.
->Unlike Stored Procedure, Function accepts only input parameters.
->Unlike Stored Procedure, Function is not used to Insert, Update, Delete data in
database table(s).
->Like Stored Procedure, Function can be nested up to 32 level.
->User Defined Function can have upto 1023 input parameters while a Stored
Procedure can have upto 2100 input parameters.
->User Defined Function can't returns XML Data Type.
->User Defined Function doesn't support Exception handling.
->User Defined Function can call only Extended Stored Procedure.
->User Defined Function doesn't support set options like set ROWCOUNT etc.
===================================================================================
==================================
Q)When to use stored procedure and when to use function?
Function can be used in Select query. For example you want to get some name by
passing some code and need to use this fucntionality in more then one select query.
In that case you can create a Function and call the function in your select query.
You can also call a function from Stored procedure select ,Insert and update query
to return the result value to your procedure.

Stored procedure can be used to execute more then one query for example you can
have select,Insert,Update all in one procedure.
For example if you want to insert a Item name to a table but you need to check for
the item name already exist or not .In this case you need both Selct and then
Insert query.
===================================================================================
==================================
Q)Explain Cursors and advantages and disadvantages of cursor?
->Cursor is a Database object which allows us to process each row and manipulate
its data. A Cursor is always associated with a Select Query and it will process
each row returned by the Select Query one by one.
->Using Cursor we can verify each row data, modify it or perform calculations which
are not possible when we get all records at once.

Why and When to use Cursor?


---------------------------
There are some conditions when we want to get record from one table and need to
insert into another with performing some logic or some conditions .For example if
we want to get value from one table row by row and need to perform some logic over
that and update /insert into another table then we can use cursors. Cursor
basically works as for/While loop.

How to write and use Cursors in SQL Server Stored Procedure?


------------------------------------------------------------
CREATE PROCEDURE PrintCustomers_Cursor
AS
BEGIN
SET NOCOUNT ON;

--DECLARE THE VARIABLES FOR HOLDING DATA.


DECLARE @CustomerId INT
,@Name VARCHAR(100)
,@Country VARCHAR(100)

--DECLARE AND SET COUNTER.


DECLARE @Counter INT
SET @Counter = 1

--DECLARE THE CURSOR FOR A QUERY.


DECLARE PrintCustomers CURSOR READ_ONLY
FOR
SELECT CustomerId, Name, Country
FROM Customers

--OPEN CURSOR.
OPEN PrintCustomers

--FETCH THE RECORD INTO THE VARIABLES.


FETCH NEXT FROM PrintCustomers INTO
@CustomerId, @Name, @Country

--LOOP UNTIL RECORDS ARE AVAILABLE.


WHILE @@FETCH_STATUS = 0
BEGIN
IF @Counter = 1
BEGIN
PRINT 'CustomerID' + CHAR(9) + 'Name' + CHAR(9) + CHAR(9) +
CHAR(9) + 'Country'
PRINT '------------------------------------'
END

--PRINT CURRENT RECORD.


PRINT CAST(@CustomerId AS VARCHAR(10)) + CHAR(9) + CHAR(9) + CHAR(9) +
@Name + CHAR(9) + @Country

--INCREMENT COUNTER.
SET @Counter = @Counter + 1

--FETCH THE NEXT RECORD INTO THE VARIABLES.


FETCH NEXT FROM PrintCustomers INTO
@CustomerId, @Name, @Country
END

--CLOSE THE CURSOR.


CLOSE PrintCustomers
DEALLOCATE PrintCustomers
END
GO

Advantages of using Cursor:


---------------------------
->Using Cursor we can perform row by row processing so we can perform row wise
validation or operations on each row.
->Cursors can provide the first few rows before the whole result set is assembled.
Without using cursors, the entire result set must be delivered before any rows are
displayed by the application. So using cursor, better response time is achieved.
->If we make updates to our without using cursors in your application then we must
send separate SQL statements to the database server to apply the changes. This can
cause the possibility of concurrency problems if the result set has changed since
it was queried by the client. In turn, this raises the possibility of lost updates.
So using cursor, better concurrency Control can be achieved.
->Cursors can be faster than a while loop but at the cost of more overhead.

Disadvantages of Cursor:
------------------------
->The major disadvantage of a Cursor is its performance issue. A Cursor can be
really slow when performing operations on large number of records and your SQL
Query may take minutes to execute and produce results.
->Thus you must wisely choose and decide on the right scenario where you want to
use a Cursor.
===================================================================================
==================================
Q) How to Remove duplicate records from a table in SQL Server?
Method1:-
---------
select distinct * into #tmp From <TableName>
delete from <TableName>
insert into <TableName>
select * from #tmp drop table #tmp

Method2:-
---------
delete from <TableName>
where EmpID in
(select EmpID from <TableName>
group by EmpId
having count(*) >1)

Method3:-
---------
WITH EmployeesCTE AS
(
SELECT *, ROW_NUMBER() OVER(PARTITION BY ID ORDER BY ID) AS RowNumber FROM
Employees
)
DELETE FROM EmployeesCTE WHERE RowNumber > 1
===================================================================================
==================================
Q) Write a query to Get nth highest and lowest salary of an employee?
To find the highest salary it is straight forward. We can simply use the Max()
function as shown below.
Select Max(Salary) from Employees

To get the second highest salary use a sub query along with Max() function as shown
below.
Select Max(Salary) from Employees where Salary < (Select Max(Salary) from
Employees)

To find nth highest salary using Sub-Query:-


--------------------------------------------
SELECT TOP 1 SALARY
FROM (
SELECT DISTINCT TOP N SALARY
FROM EMPLOYEES
ORDER BY SALARY DESC
) RESULT
ORDER BY SALARY

To find nth highest salary using CTE:-


--------------------------------------
WITH RESULT AS
(
SELECT SALARY, DENSE_RANK() OVER(ORDER BY SALARY DESC) AS DENSERANK FROM
EMPLOYEES
)
SELECT MAX(SALARY) FROM RESULT WHERE DENSERANK = N
===================================================================================
==================================
Q) SQL query to get organization hierarchy?
Declare @ID int ;
Set @ID = 7;

WITH EmployeeCTE AS
(
Select EmployeeId, EmployeeName, ManagerID
From Employees
Where EmployeeId = @ID

UNION ALL

Select Employees.EmployeeId , Employees.EmployeeName,


Employees.ManagerID
From Employees
JOIN EmployeeCTE
ON Employees.EmployeeId = EmployeeCTE.ManagerID
)

Select E1.EmployeeName, ISNULL(E2.EmployeeName, 'No Boss') as ManagerName


From EmployeeCTE E1
LEFT Join EmployeeCTE E2
ON E1.ManagerID = E2.EmployeeId
===================================================================================
==================================
Q) SQL query to find employees hired in last n months?
-- Replace N with number of months
Select * FROM Employees Where DATEDIFF(MONTH, HireDate, GETDATE()) Between 1 and N
===================================================================================
==================================
Q) Transform rows into columns in sql server?
Using PIVOT operator we can very easily transform rows to columns.
Select Country, City1, City2, City3
From
(
Select Country, City, 'City'+ cast(row_number() over(partition by Country order by
Country) as varchar(10)) ColumnSequence
from Countries
) Temp
pivot
(
max(City)
for ColumnSequence in (City1, City2, City3)
) Piv
===================================================================================
==================================
Q) SQL query to find rows that contain only numerical data?
SELECT Value FROM TestTable WHERE ISNUMERIC(Value) = 1
ISNUMERIC function returns 1 when the input expression evaluates to a valid numeric
data type, otherwise it returns 0.
===================================================================================
==================================
Q) SQL Query to find department with highest number of employees?
SELECT TOP 1 DepartmentName
FROM Employees
JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID
GROUP BY DepartmentName
ORDER BY COUNT(*) DESC
===================================================================================
==================================
Q) Difference between inner join and left join?
-> INNER JOIN returns only the matching rows between the tables involved in the
JOIN.

SELECT EmployeeName, DepartmentName


FROM Employees
INNER JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID

-> LEFT JOIN returns all rows from left table including non-matching rows.

SELECT EmployeeName, DepartmentName


FROM Employees
LEFT JOIN Departments
ON Employees.DepartmentID = Departments.DepartmentID

Q) What is the difference between INNER JOIN and RIGHT JOIN ?


INNER JOIN returns only the matching rows between the tables involved in the JOIN,
where as RIGHT JOIN returns all the rows from the right table including the NON-
MATCHING rows.

Q) What is the difference between INNER JOIN and FULL JOIN ?


FULL JOIN returns all the rows from both the left and right tables including the
NON-MATCHING rows.

Q) What is the Difference between INNER JOIN and JOIN?


There is no difference they are exactly the same. Similarly there is also no
difference between
LEFT JOIN and LEFT OUTER JOIN
RIGHT JOIN and RIGHT OUTER JOIN
FULL JOIN and FULL OUTER JOIN
===================================================================================
==================================
Q) Write a query to join 3 the tables and retrieve EmployeeName, DepartmentName and
Gender.?
SELECT EmployeeName, DepartmentName, Gender
FROM Employees
JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID
JOIN Genders ON Employees.GenderID = Genders.GenderID

Q) Write a query to show the total number of employees by DEPARTMENT and by


GENDER.?
SELECT DepartmentName, Gender, COUNT(*) as TotalEmployees
FROM Employees
JOIN Departments ON Employees.DepartmentID = Departments.DepartmentID
JOIN Genders ON Employees.GenderID = Genders.GenderID
GROUP BY DepartmentName, Gender
ORDER BY DepartmentName, Gender
===================================================================================
==================================
Q) Real time example for right join?
Question 1: Can you list different types of JOINS available in SQL Server
Answer: Inner Join, Left Join, Right Join, Full Join and Cross Join

Question 2: Can you tell me the purpose of Right Join?


Answer: Right Join returns all rows from the Right Table irrespective of whether a
match exists in the left table or not.

Question 3: Can you give me an example?


Answer: Consider Departments and Employees tables.

In this case we use RIGHT JOIN To retrieve all Department and Employee names,
irrespective of whether a Department has Employees or not.

Select DepartmentName, EmployeeName


From Employees
Right Join Departments
On Employees.DepartmentID = Departments.DepartmentID

Question 4: I accept you have understood the purpose of Right Join. Based on the
above 2 tables, can you give me any other business case for using Right Join.

Another business case for using RIGHT JOIN on the above 2 tables is to retrieve all
the Department Names and the total number of Employees with in each department.

SQL Query with Right Join:


--------------------------
Select DepartmentName, Count(Employees.DepartmentID) as TotalEmployees
From Employees
Right Join Departments
ON Departments.DepartmentID = Employees.DepartmentID
Group By DepartmentName
Order By TotalEmployees
===================================================================================
==================================
Q) Can we join two tables without primary foreign key relation?
Yes, we can join two tables without primary foreign key relation as long as the
column values involved in the join can be converted to one type.

ID column in Departments table is not the primary Key and DepartmentId column in
Employees table is not the foreign key. But we can still join these tables using ID
column from Departments table and DepartmentId column from Employees table, as both
the columns involved in the join have same data type i.e int.
Select Employees.Name as EmployeeName, Departments.Name as DepartmentName
from Employees
join Departments on Departments.ID = Employees.DepartmentId

The obious next question is, if primary foreign key relation is not mandatory for 2
tables to be joined then what is the use of these keys?
Primary key enforces uniqueness of values over one or more columns. Since ID is not
a primary key in Departments table, 2 or more departments may end up having same ID
value, which makes it impossible to distinguish between them based on the ID column
value.

Foreign key enforces referential integrity. Without foreign key constraint on


DepartmentId column in Employees table, it is possible to insert a row into
Employees table with a value for DepartmentId column that does not exist in
Departments table.

The following insert statement, successfully inserts a new Employee into Employees
table whose DepartmentId is 100. But we don't have a department with ID = 100 in
Departments table. This means this employee row is an orphan row, and the
referential integrity is lost as result
Insert into Employees values (8, 'Mary', 'Female', 80000, 100)

If we have had a foreign key constraint on DepartmentId column in Employees table,


the following insert statement would have failed with the following error.
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the FOREIGN KEY constraint. The conflict
occurred in database "Sample", table "dbo.Departments", column 'ID'.
===================================================================================
==================================
Q) Sql query to select all names that start with a given letter without like
operator?
The following 3 queries retrieve all student rows whose Name starts with letter
'M'. Notice none of the queries are using the LIKE operator.
SELECT * FROM Students WHERE CHARINDEX('M',Name) = 1
SELECT * FROM Students WHERE LEFT(Name, 1) = 'M'
SELECT * FROM Students WHERE SUBSTRING(Name, 1, 1) = 'M'
===================================================================================
==================================
Q) Difference between blocking and deadlocking?
Blocking : Occurs if a transaction tries to acquire an incompatible lock on a
resource that another transaction has already locked. The blocked transaction
remains blocked until the blocking transaction releases the lock.

Example : Open 2 instances of SQL Server Management studio. From the first window
execute Transaction 1 code and from the second window execute Transaction 2 code.
Notice that Transaction 2 is blocked by Transaction 1. Transaction 2 is allowed to
move forward only when Transaction 1 completes.

--Transaction 1
Begin Tran
Update TableA set Name='Mark Transaction 1' where Id = 1
Waitfor Delay '00:00:10'
Commit Transaction

--Transaction 2
Begin Tran
Update TableA set Name='Mark Transaction 2' where Id = 1
Commit Transaction

Deadlock : Occurs when two or more transactions have a resource locked, and each
transaction requests a lock on the resource that another transaction has already
locked. Neither of the transactions here can move forward, as each one is waiting
for the other to release the lock. So in this case, SQL Server intervenes and ends
the deadlock by cancelling one of the transactions, so the other transaction can
move forward.

Example : Open 2 instances of SQL Server Management studio. From the first window
execute Transaction 1 code and from the second window execute Transaction 2 code.
Notice that there is a deadlock between Transaction 1 and Transaction 2.

-- Transaction 1
Begin Tran
Update TableA Set Name = 'Mark Transaction 1' where Id = 1

-- From Transaction 2 window execute the first update statement

Update TableB Set Name = 'Mary Transaction 1' where Id = 1

-- From Transaction 2 window execute the second update statement


Commit Transaction

-- Transaction 2
Begin Tran
Update TableB Set Name = 'Mark Transaction 2' where Id = 1

-- From Transaction 1 window execute the second update statement

Update TableA Set Name = 'Mary Transaction 2' where Id = 1

-- After a few seconds notice that one of the transactions complete


-- successfully while the other transaction is made the deadlock victim
Commit Transaction
===================================================================================
==================================
Q) Different Types of SQL Joins?
Sql joins are used to fetch/retrieve data from two or more data tables, based on a
join condition.
A join condition is a relationship among some columns in the data tables that take
part in Sql join. Basically data tables are related to each other with keys. We use
these keys relationship in sql joins.

Types of Joins:-
-----------------
In Sql Server we have only three types of joins. Using these joins we fetch the
data from multiple tables based on condition.

1) Inner Join:-
---------------
Inner join returns only those records/rows that match in both the tables.

Syntax:-
---------
Select * from table_1 as t1
inner join table_2 as t2
on t1.IDcol=t2.IDcol

2) Outer Join:-
---------------
We have three types of Outer Join.

A) Left Outer Join:-


--------------------
Left outer join returns all records/rows from left table and from right table
returns only matched records. If there are no columns matching in the right table,
it returns NULL values.
Syntax:-
---------
Select * from table_1 as t1
left outer join table_2 as t2
on t1.IDcol=t2.IDcol

B) Right Outer Join:-


---------------------
Right outer join returns all records/rows from right table and from left table
returns only matched records. If there are no columns matching in the left table,
it returns NULL values.

Syntax:-
---------
Select * from table_1 as t1
right outer join table_2 as t2
on t1.IDcol=t2.IDcol

C) Full Outer Join:-


---------------------
Full outer join combines left outer join and right outer join. This join returns
all records/rows from both the tables.If there are no columns matching in the both
tables, it returns NULL values.

Syntax:-
---------
Select * from table_1 as t1
full outer join table_2 as t2
on t1.IDcol=t2.IDcol

3) Cross Join:-
---------------
Cross join is a cartesian join means cartesian product of both the tables. This
join does not need any condition to join two tables. This join returns records/rows
that are multiplication of record number from both the tables means each row on
left table will related to each row of right table.

Syntax:-
---------
Select * from table_1
cross join table_2

4) Self Join:-
--------------
-> Self join is used to join a database table to itself, particularly when the
table has a Foreign key that references its own Primary Key.
-> Basically we have only three types of joins : Inner join, Outer join and Cross
join.
We use any of these three JOINS to join a table to itself. Hence Self join is not a
type of Sql join.

Sample Query:
-------------
select e.id,e.name,e.supid as managerid, ei.name as managername
from emp e
left join emp ei
on e.supid=ei.id;
===================================================================================
==================================
Q) What is normalization and de normalization?
-> Normalization is the process of efficiently organizing data to minimize data
redundency(data duplication), which in terms ensure data consistency.
-> Generally we organize the data up to third normal form. We rarely use the fourth
and fifth normal form.

Problems of Data Redundency:-


-----------------------------
-> Disk Space wastage.
-> Data Inconsistency.
-> DML Quries becom slow.

Benefits :-
-----------
-> Eliminate data redundancy
-> Improve performance
-> Query optimization
-> Faster update due to less number of columns in one table
-> Index improvement

First Normal Form (1NF):-


-------------------------
-> The data in each column should be automic. No multile values seperated by comma.
-> A database table is said to be in 1NF if it contains no repeating columns.
-> The primary key of new database tables may be a composite key

Second Normal Form (2NF):-


--------------------------
-> The table meets all the conditions of 1NF.
-> Move redundent data to seperate table.
-> Create relationship between tables using foreign keys.

Third Normal Form (3NF):-


------------------------
-> The table meets all the conditions of 1NF & 2NF.
-> Does not contain columns that are not fully dependent upon primary key.

Boyce Code Normal Form (BCNF):-


-------------------------------
-> A database table is said to be in BCNF if it is in 3NF and contains each and
every determinant as a candidate key.

The process of converting the table into BCNF is as follows:


1) Remove the non trival functional dependency.
2) Make separate table for the determinants.

Fourth Normal Form (4NF):-


--------------------------
-> A database table is said to be in 4NF if it is in BCNF and primary key has one-
to-one relationship to all non keys fields or We can also said a table to be in 4NF
if it is in BCNF and contains no multi-valued dependencies.

The process of converting the table into 4NF is as follows:


1) Remove the multivalued dependency.
2) Make separate table for multivalued Fields.

Fifth Normal Form (5NF):-


-------------------------
-> A database table is said to be in 5NF if it is in 4NF and contains no redundant
values or We can also said a table to be in 5NF if it is in 4NF and contains no
join dependencies.

The process of converting the table into 5NF is as follows:


1) Remove the join dependency.
2) Break the database table into smaller and smaller tables to remove all data
redundancy.

De-normalization:-
------------------
The process of adding redundant data to get rid of complex join, in order to
optimize database performance. This is done to speed up database access by moving
from higher to lower form of normalization.
===================================================================================
==================================
Q) SQL Server 2012 New Features and Programmability Enhancements?
T-SQL THROW Statement:-
-----------------------
Now SQL Server 2012 has improved error handling by introducing throw statement for
throwing exception in T-SQL. However this statement has some limitations and does
not provide powerful features like RAISERROR.

Conversion Functions:-
----------------------
SQL Serve 2012 has support for new conversion functions TRY_CONVERT, and TRY_PARSE
for convering numeric, date, and time values to desired format. These functions are
very helpful while programming T-SQL.

T-SQL built-in pagination:-


---------------------------
SQL Server 2012 also supports built-in pagination with the help of OFFSET and FETCH
like MySQL. Actually, OFFSET and FETCH will act as a replacement for TOP in SQL
Server.

Example:-
---------
--Suppose Employee tables has 500 records
--Below query skip 200 rows and fetch the next 20 records
SELECT EmpID, EmpName, Salary FROM dbo.Employee
ORDER BY EmpID
OFFSET 200 ROWS
FETCH NEXT 20 ROWS ONLY

T-SQL Sequence:-
----------------
SQL Server 2012 also supports sequence like Oracle database. It works like as
IDENTITY field without being a field. The main advantage of sequence is that you
can use it in the same way as GUIDs and with better performance than GUIDs when
used as a clustered index key.

Example:-
---------
--Create Sequence object
CREATE SEQUENCE objSequence
START WITH 1
INCREMENT BY 1;

--Create Employee object


DECLARE @Employee TABLE
(
ID int NOT NULL PRIMARY KEY,
FullName nvarchar(100) NOT NULL
)
--Insert values
INSERT @Employee (ID, FullName)
VALUES (NEXT VALUE FOR objSequence, 'Mohan'),
(NEXT VALUE FOR objSequence, 'Deepak'),
(NEXT VALUE FOR objSequence, 'Pavan');

--Show data
SELECT * FROM @Employee

Metadata Discovery Enhancements:-


---------------------------------
SQL Server 2012 also has improved metadata discovery, which allow you to determine
the shape of projected output from queries, tables, stored procedure, views, and
other objects. As a result SQL Server supports business intellisense and debugging.

T-SQL Format() Function:-


-------------------------
SQL Server 2012 introduces a new function format() for formatting string data like
as C#. It is a CLR based function.
SELECT FORMAT(GETDATE(), 'yyyy-MM-dd') AS [ISO Formatted Date], FORMAT(GETDATE(),
'yyyy-MM-dd hh:mm:ss') AS [Full ISO], FORMAT(GETDATE(), 'MMMM dd, yyyy') AS [Long-
EN Date], FORMAT(22.7, 'C', 'en-US') AS [US Currency], FORMAT(99 * 2.226,
'000.000') AS [Padded Decimal], FORMAT(12345678, '0,0') AS [Commas in Large
Numbers]
===================================================================================
==================================
Q) String Functions in SQL Server?
CHARINDEX:-
-----------
The CHARINDEX function searches an expression for another expression and returns
its starting position if found.
Syntax:
-------
CHARINDEX ( expressionToFind ,expressionToSearch [ , start_location ] )
Example:-
---------
DECLARE @expressionToSearch [varchar](MAX);
DECLARE @expressionToFind [varchar](MAX);
SET @expressionToSearch ='SQL SERVER CONTAIN STRING FUNCTION'
SET @expressionToFind='SERVER';
SELECT CHARINDEX(@expressionToFind,@expressionToSearch ) AS LOCATION_IS;

LEFT:-
-----
The LEFT function returns the left part of a character string with the specified
number of characters.
Syntax:
-------
LEFT ( character_expression , integer_expression )

REPLACE:-
--------
REPLACE function Replaces all occurrences of a specified string value with another
string value.
Syntax:
-------
REPLACE ( string_expression , string_pattern , string_replacement )
Example:-
---------
DECLARE @PATTERN [nvarchar](MAX);
DECLARE @FIND [nvarchar](MAX);
DECLARE @REPLACEWITH [nvarchar](MAX);
SET @PATTERN='I LIKE ENGLISH';
SET @FIND='ENGLISH';
SET @REPLACEWITH='HINDI';
SELECT REPLACE(@PATTERN,@FIND,@REPLACEWITH) [REPLACE];

SUBSTRING:-
-----------
The SUBSTRING function returns part of a character, binary, text, or image
expression in SQL Server.
Syntax:-
--------
SUBSTRING ( expression ,start , length )
Return Type:-
------------
character or binary
Example:-
---------
DECLARE @STRING [nvarchar](MAX);
SET @STRING='ABCDEFGHIJKLMNOP';
SELECT SUBSTRING(@STRING,1,3) [STRING] UNION ALL
SELECT SUBSTRING(@STRING,3,4) [STRING] UNION ALL
SELECT SUBSTRING(@STRING,2,5) [STRING] UNION ALL
SELECT SUBSTRING(@STRING,7,4) [STRING] UNION ALL
SELECT SUBSTRING(@STRING,6,5) [STRING]

STR:-
-----
The STR function returns character data converted from numeric data.
Syntax:
-------
STR ( float_expression [ , length [ , decimal ] ] )
Return Type:
------------
varchar
Example:
--------
DECLARE @FLOAT varchar(60);
SET @FLOAT=12345.12345;
SELECT STR(@FLOAT,11,5) [STR] ,'FULL STRING'[DISCRIPTION] UNION ALL
SELECT STR(@FLOAT,11,3) [STR] ,'STRING CONTAIN 2 BLANK SPACE ' UNION ALL
SELECT STR(@FLOAT,11,1) [STR] ,'STRING CONTAIN 4 BLANK SPACE ' UNION ALL
SELECT STR(@FLOAT,4,1) [STR] ,'STRING CONVERT INTO *' UNION ALL
SELECT STR(@FLOAT,4,1) [STR] ,'STRING CONVERT INTO *'
GO

Cast() Function:-
-----------------
The Cast() function is used to convert a data type variable or data from one data
type to another data type. The Cast() function provides a data type to a dynamic
parameter (?) or a NULL value.

Syntax:-
--------
CAST ( [Expression] AS Datatype)
The data type to which you are casting an expression is the target type. The data
type of the expression from which you are casting is the source type.

Example:-
---------
DECLARE @A varchar(2)
DECLARE @B varchar(2)
DECLARE @C varchar(2)
set @A=25
set @B=15
set @C=33
Select CAST(@A as int) + CAST(@B as int) +CAST (@C as int) as Result

Convert() Function:-
--------------------
When you convert expressions from one type to another, in many cases there will be
a need within a stored procedure or other routine to convert data from a datetime
type to a varchar type. The Convert function is used for such things. The CONVERT()
function can be used to display date/time data in various formats.

Syntax:
-------
CONVERT(data_type(length), expression, style)
Style - style values for datetime or smalldatetime conversion to character data.
Add 100 to a style value to get a four-place year that includes the century (yyyy).

Example:
--------
In this example we take a style value 108 which defines the following format:
hh:mm:ss
Now use the above style in the following query:
select convert(varchar(20),GETDATE(),108)
====================================================COMPLETED======================
==================================

===================================================================================
==================================
C# Technical Programs:-
=======================

Given an array of ints, write a C# method to total all the values that are even
numbers?
static long TotalAllEvenNumbers(int[] intArray)
{
return intArray.Where(i => i % 2 == 0).Sum(i => i);
}
===================================================================================
==================================
What is the output of the short program below? Explain your answer?
class Program
{
static String location;
static DateTime time;

static void Main() {


Console.WriteLine(location == null ? "location is null" : location);
Console.WriteLine(time == null ? "time is null" : time.ToString());
}
}
The output will be:
location is null
1/1/0001 12:00:00 AM
===================================================================================
==================================
Is the comparison of time and null in the if statement below valid or not? Why or
why not?
static DateTime time;
/* ... */
if (time == null)
{
/* do something */
}
One might think that, since a DateTime variable can never be null (it is
automatically initialized to Jan 1, 0001), the compiler would complain when a
DateTime variable is compared to null. However, due to type coercion, the compiler
does allow it, which can potentially lead to headfakes and pull-out-your-hair bugs.

Example:-
---------
double x = 5.0;
int y = 5;
Console.WriteLine(x == y); // outputs true
===================================================================================
==================================
What will be the output for the below mentioned lines in JQuery?
alert('5' + 5 + 5); Output= 555
alert(5 + 5 + '5'); Output=105
alert(5 + '5' + '5'); Output=555
alert(5 + '5' ); Output=55
===================================================================================
==================================
//Write a program for Count Characters in String.?
const string t2 = "Mary had a little lamb.";
int result = 0;
foreach (char c in t2)
{
if (!char.IsWhiteSpace(c))//For Characters
{
result++;
}
if (char.IsLetter(c))//For Letters
{
result++;
}
if (char.IsDigit(c))//For Digits
{
result++;
}
}
Console.WriteLine(result);
===================================================================================
==================================
//Write a program to get unique chracter from the string?
HashSet<char> chars = new HashSet<char>();
string s = "aabbcccddeefddg";
foreach (char c in s)
{
chars.Add(c);
}
foreach (char c in chars)
{
Console.WriteLine(c);
}
(OR)
string code = "AABBDDCCRRFF";
string answer = new String(code.Distinct().ToArray());
(OR)
string str = "hai rakesh";
string table = "";
string result = "";
// Loop over each character.
foreach (char value in str)
{
// See if character is in the table.
if (table.IndexOf(value) == -1)
{
// Append to the table and the result.
table += value;
result += value;
}
}
Console.WriteLine(result);
===================================================================================
==================================(Q) Write a program to swap every two words?
Input:- Rakesh belongs to Vijayawada
Output:- belongs Rakesh Vijayawada to

string sentence = "I have created a variable to create";


string[] words = sentence.Split(' ');
string newSentance = string.Empty;
for (int i = 0; i < words.Length; i++)
{
if (i + 1 < words.Length)
{
if (!string.IsNullOrEmpty(newSentance))
newSentance += " ";
newSentance += words[i + 1];
newSentance += " ";
newSentance += words[i];
i++;
}
}
Console.WriteLine(newSentance);
Console.ReadLine();
===================================================================================
==================================
Armstrong number is a number that is equal to the sum of cubes of its digits
For example, 371 is an Armstrong number since 3**3 + 7**3 + 1**3 = 371.
A Prime Number can be divided evenly only by 1, or itself. And it must be a whole
number greater than 1. Example: 5 can only be divided evenly by 1 or 5, so it is a
prime number. But 6 can be divided evenly by 1, 2, 3 and 6 so it is NOT a prime
number (it is a composite number).

The factorial function (symbol: !) means to multiply a series of descending natural


numbers. Examples:
4! = 4 � 3 � 2 � 1 = 24

a series of numbers in which each number ( Fibonacci number ) is the sum of the two
preceding numbers. The simplest is the series 1, 1, 2, 3, 5, 8, etc.
The next number is found by adding up the two numbers before it.

If the number is not divisible by 2 then that number will be an Odd number.
If the number is divisible by 2 then that number will be an Even number.
===================================================================================
==================================
//Subtract the largest even number and smallest odd number in the given array
elements?
int?[] Numbers = { 555, 3, 1, 20, 1000 };

int? largestEvenNumber = null;


int? smallestOddNumber = null;

foreach (int i in Numbers)


{
if ((i % 2) == 0)
{
if (!largestEvenNumber.HasValue || i > largestEvenNumber)
{
largestEvenNumber = i;
}
}
else
{
if (!smallestOddNumber.HasValue || i < smallestOddNumber)
{
smallestOddNumber = i;
}
}
}

if (largestEvenNumber == null)
{
Console.WriteLine("Array does not contain any even number");
}
else
{
Console.WriteLine("Largest even number = " + largestEvenNumber);
}

if (smallestOddNumber == null)
{
Console.WriteLine("Array does not contain any odd number");
}
else
{
Console.WriteLine("Smallest odd number = " + smallestOddNumber);
}
if (largestEvenNumber != null && smallestOddNumber != null)
{
Console.WriteLine("{0} - {1} = {2}",
largestEvenNumber,smallestOddNumber, (largestEvenNumber -
smallestOddNumber));
}
===================================================================================
==================================
// Largest and smallest number in an array?

int minint = array[0];


int maxint = array[0];
foreach (int value in array)
{
if (value < minint)
minint = value;
if (value > maxint)
maxint = value;
}
===================================================================================
==================================
//Subtract the largest even number and smallest odd number in the given array
elements By using Linq?
int?[] Numbers = { 555, 3, 1, 20, 1000 };

int? largestEvenNumber = Numbers.Where(x => x % 2 == 0).Max();


int? smallestOddNumber = Numbers.Where(x => x % 2 != 0).Min();

if (largestEvenNumber == null)
{
Console.WriteLine("Array does not contain any even number");
}
else
{
Console.WriteLine("Largest even number = " + largestEvenNumber);
}

if (smallestOddNumber == null)
{
Console.WriteLine("Array does not contain any odd number");
}
else
{
Console.WriteLine("Smallest odd number = " + smallestOddNumber);
}

if (largestEvenNumber != null && smallestOddNumber != null)


{
Console.WriteLine("{0} - {1} = {2}", largestEvenNumber,
smallestOddNumber, (largestEvenNumber - smallestOddNumber));
}
===================================================================================
==================================//Program to check if the user input is a string
or an integer?

Console.WriteLine("Please type your input and press Enter key");


string strInput = Console.ReadLine();
int result = 0;
if (int.TryParse(strInput, out result))
{
Console.WriteLine("Your input {0} is a number", result);
}
else
{
Console.WriteLine("Your input {0} is NOT a number", strInput);
}
===================================================================================
==================================
//Reverse a string with Builtin Functions?

string reverseString = string.Empty;


Console.WriteLine("Please enter your string");
string word = Console.ReadLine();
char[] charArray = word.ToCharArray();
Array.Reverse(charArray);
Console.WriteLine(charArray);
===================================================================================
==================================
// Reverse a string without Builtin Functions?

string reverseString = string.Empty;


Console.WriteLine("Please enter your string");
string word = Console.ReadLine();
for (int i = word.Length - 1; i >= 0; i--)
{
reverseString += word[i];
}
Console.WriteLine(reverseString);
===================================================================================
==================================
// Reverse a string without Builtin Functions in Different Ways of writing?

string Str, reversestring = string.Empty;


Console.Write("Enter A String : ");
Str = Console.ReadLine();
int Length = Str.Length - 1;
while (Length >= 0)
{
reversestring = reversestring + Str[Length];
Length--;
}
Console.WriteLine("Reverse String Is {0}", reversestring);
===================================================================================
==================================
// program to determine whether or not a word is a palindrom?
string reverseString = string.Empty;
Console.WriteLine("Please enter your string");
string word = Console.ReadLine();
for (int i = word.Length - 1; i >= 0; i--)
{
reverseString += word[i];
}
if (word == reverseString)
{ Console.WriteLine("The string is pallindrome"); }
else
{ Console.WriteLine("The string is not pallindrome"); }
===================================================================================
==================================
// Palindrome Numbers Between 1 and 10000?
for (int k = 1; k <= 10000; k++)
{
string reverseNum = string.Empty;
string number = k.ToString();
for (int i = number.Length - 1; i >= 0; i--)
{
reverseNum += number[i];
}
if (number == reverseNum)
{
Console.WriteLine(k);
}
}
===================================================================================
==================================//Reverse a Number?
int reverseNum = 0;
Console.WriteLine("Please enter your Number");
int number = int.Parse(Console.ReadLine());
while (number > 0)
{
int rem = number % 10;
reverseNum = (reverseNum * 10) + rem;
number = number / 10;
}
Console.WriteLine(reverseNum);
===================================================================================
==================================
// program to Check Armstrong Number or not?
int sum = 0;
Console.WriteLine("Please enter your Number");
int number = int.Parse(Console.ReadLine());
for (int i = number; i > 0; i = i / 10)
{
int remainder = i % 10;
sum = sum + remainder * remainder * remainder;
}
if (sum == number)
{ Console.WriteLine("the number is Armstrong Number"); }
else
{ Console.WriteLine("the number is not Armstrong Number"); }
===================================================================================
==================================
//Armstrong Numbers Between 1 and 10000?
for (int k = 1; k <= 10000; k++)
{
int sum = 0;
for (int i = k; i > 0; i = i / 10)
{
int remainder = i % 10;
sum = sum + remainder * remainder * remainder;
}
if (sum == k)
{
Console.WriteLine(k);
}
}
===================================================================================
==================================
// Swap two numbers without using temporary variable?
int first, second;
first = 1;
second = 2;
first = first + second;
second = first - second;
first = first - second;
Console.WriteLine("After swapping the first number is" + first);
Console.WriteLine("After swapping the second number is" + second);
===================================================================================
==================================
//Program to Check Whether the Given Number is a Prime number?
Console.Write("Enter a Number : ");
int k = 0;
int num = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= num; i++)
{
if (num % i == 0)
{
k++;
}
}
if (k == 2)
{
Console.WriteLine("Entered Number is a Prime Number");
}
else
{
Console.WriteLine("Not a Prime Number");
}
===================================================================================
==================================
//Program to Print Prime number between 1 to 1000?
for (int i = 1; i <= 1000; i++)
{
int k = 0;
for (int j = 1; j <= i; j++)
{
if (i % j == 0)
{
k++;
}
}
if (k == 2)
{
Console.WriteLine(i);
}
}
===================================================================================
==================================
//Factorial of Given Number?
int fact;
Console.WriteLine("Enter the Number :");
int number = int.Parse(Console.ReadLine());
fact = number;
for (int i = number - 1; i >= 1; i--)
{
fact = fact * i;
}
Console.WriteLine("\nFactorial of Given Number is: " + fact);
===================================================================================
==================================
//Generate Fibonacci Series?
int i, count, f1 = 0, f2 = 1, f3 = 0;
Console.Write("Enter the Limit : ");
count = int.Parse(Console.ReadLine());
Console.WriteLine(f1);
Console.WriteLine(f2);
for (i = 0; i <= count; i++)
{
f3 = f1 + f2;
Console.WriteLine(f3);
f1 = f2;
f2 = f3;
}
===================================================================================
==================================
// program to sum of N numbers?
int i, sum = 0; int number;
Console.Write("Enter the Nth Number : ");
number = int.Parse(Console.ReadLine());
for (i = 0; i <= number; i++)
{
sum = sum + i;
}
Console.WriteLine("\nSum of N Numbers : " + sum);
===================================================================================
==================================
// program to find Even & Odd Number?
int i;
Console.Write("Enter a Number : ");
i = int.Parse(Console.ReadLine());
if (i % 2 == 0)
{
Console.Write("Entered Number is an Even Number");
}
else
{
Console.Write("Entered Number is an Odd Number");
}
===================================================================================
==================================
// Program to Finding duplicate integers in an array and display how many times
they occurred?
int[] values = new[] { 1, 2, 3, 4, 5, 4, 4, 3 };
var groups = values.GroupBy(v => v);
foreach (var group in groups)
Console.WriteLine("Value {0} has {1} items", group.Key,
group.Count());
===================================================================================
==================================
// Program to find duplicate items in list<>?
List<string> list = new List<string>() { "a", "a", "b", "b", "r",
"t" };
var dups = list.GroupBy(x => x)
.Where(x => x.Count() > 1)
.Select(x => x.Key)
.ToList();
foreach (var dup in dups)
Console.WriteLine("Duplicate item - {0} ", dup);
===================================================================================
==================================
//Sorting Algorithm - BubbleSort?
int[] array = { 3, 2, 2, 2, 5, 5, 4, 1 };
int i, j, temporary,length;
length = array.Length;

for (i = length - 1; i > 0; i--)


{
for (j = 0; j < i; j++)
{
if (array[j] > array[j + 1])
{
temporary = array[j + 1];
array[j + 1] = array[j];
array[j] = temporary;
}
}
}
===================================================================================
==================================
// program to display the Pyramid Shape?
int numberoflayer = 9, space;
Console.WriteLine("Print paramid");
for (int i = 1; i <= numberoflayer; i++)// Total number of layer for
pramid
{
for (space = 1; space <= (numberoflayer - i); space++)// Loop For
Space
{
Console.Write(" ");
}
for (int j = 1; j <= i; j++)//increase the value
{
Console.Write("*");
}
for (int k = (i - 1); k >= 1; k--)//decrease the value
{
Console.Write("*");
}
Console.WriteLine();
}
===================================================================================
==================================
//program to display the Triangle Shape?
int val = 5;
for (int i = 1; i <= val; i++)
{
for (int j = 1; j <= i; j++)
{
Console.Write("");
}
for (int k = 1; k <= i; k++)
{
Console.Write("*");
}
Console.WriteLine("");
}
===================================================================================
==================================
//count of a specific character in a string?
string test = "key1=value1&key2=value2&key3=value3";
int cnt = 0, cnt1 = 0, cnt2 = 0;
foreach (char c in test)
{
if (c == '&')
cnt++;
}
Console.WriteLine(cnt);
(OR)
cnt1 = test.Count(x => x == '&');
Console.WriteLine(cnt1);
(OR)
cnt2 = test.Split('&').Length - 1;
Console.WriteLine(cnt2);
===================================================================================
==================================
//C# program to find sum of digits of a number using Recursion?
int num, result;
pro pg = new pro();
Console.WriteLine("Enter the Number : ");
num = int.Parse(Console.ReadLine());
result = pg.sum(num);
Console.WriteLine("Sum of Digits in {0} is {1}", num, result);
Console.ReadLine();
Console.ReadLine();

internal class pro


{
public int sum(int num)
{
if (num != 0)
{
return (num % 10 + sum(num / 10));
}
else
{
return 0;
}
}
}
===================================================================================
==================================
//program that removes duplicate chars?
string str = "hai rakesh";
string table = "";
string result = "";
// Loop over each character.
foreach (char value in str)
{
// See if character is in the table.
if (table.IndexOf(value) == -1)
{
// Append to the table and the result.
table += value;
result += value;
}
}
Console.WriteLine(result);
===================================================================================
==================================
// Program to find FizzBuzz number?
for (int i = 1; i <= 100; i++)
{
bool fizz = i % 3 == 0;
bool buzz = i % 5 == 0;
if (fizz && buzz)
Console.WriteLine("FizzBuzz");
else if (fizz)
Console.WriteLine("Fizz");
else if (buzz)
Console.WriteLine("Buzz");
else
Console.WriteLine(i);
}
===================================================================================
==================================
// Removing Duplicate entries through traditional for loop?
int[] inputArray = { 3, 2, 2, 2, 5, 5, 4, 1 };

int length = inputArray.Length;


for (int i = 0; i < length; i++)
{
for (int j = (i + 1); j < length; )
{
if (inputArray[i] == inputArray[j])
{
for (int k = j; k < length - 1; k++)
{
inputArray[k] = inputArray[k + 1];
}
length--;
}
else
{
j++;
}
}
}
int[] distinctArray = new int[length];
for (int i = 0; i < length; i++)
distinctArray[i] = inputArray[i];

Console.WriteLine("The Array :");


foreach (int aray in distinctArray)
Console.Write(aray + " ");
===================================================================================
==================================
// Delete Duplicate elements through ArrayList/List Contain method?
System.Collections.ArrayList distinctArray = new
System.Collections.ArrayList();

foreach (string element in inputArray)


{
if (!distinctArray.Contains(element))
distinctArray.Add(element);
}
===================================================================================
==================================
// program to find if an array contains duplicate?
int[] inputArray = { 3, 2, 2, 2, 5, 5, 4, 1 };
Dictionary<int, int> d = new Dictionary<int, int>();
foreach (int i in inputArray)
{
if (d.ContainsKey(i))
Console.WriteLine("Duplicated Array");
else
d.Add(i,1);
}
===================================================================================
==================================
// The Most frequent Number in an array?
var query = (from item in array
group item by item into g
orderby g.Count() descending
select g.Key).First();
(OR)
var query = array.GroupBy(item => item).OrderByDescending(g =>
g.Count()).Select(g => g.Key).First();
===================================================================================
==================================
// program to move zeros to end of array?
int[] arr = { 1, 2, 0, 0, 0, 3, 6 };
int count = 0; // Count of non-zero elements
for (int i = 0; i < arr.Length; i++)
if (arr[i] != 0)
arr[count++] = arr[i]; // here count is
while (count < arr.Length)
arr[count++] = 0;
foreach (int aray in arr)
Console.Write(aray + " ");
===================================================================================
==================================
// how to find the missing number in a list?
List<int> list = new List<int>() { 6, 2, 4, 1, 9, 7, 3, 10, 15, 19, 11, 18,
13, 22, 24, 20, 27, 31, 25, 28 };
list.Sort();
var firstNumber = list.First();
var lastNumber = list.Last();
var range = Enumerable.Range(firstNumber, lastNumber - firstNumber);
var missingNumbers = range.Except(list);
// Calling the Extension Method in the List of type int
foreach (var number in missingNumbers)
{
Console.Write("{0} ", number);
}
===================================================================================
==================================
// Merge two arrays and return sorted array in c#?
string[] one = new string[] { "a", "b" };
string[] two = new string[] { "c", "d" };
string[] three= new string[one.Length + two.Length];;
int idx = 0;
for (int i = 0; i < one.Length; i++)
three[idx++] = one[i];
for (int j = 0; j < two.Length; j++)
three[idx++] = two[j];
===================================================================================
==================================
// Program to Calculate LCM and GCD (HCF) in C#?
int a, b, Num1, Num2, temp, LCM, GCD;
Console.WriteLine("Calculate LCM and GCD\nEnter the two numbers to
Calculate..");
a = int.Parse(Console.ReadLine());
b = int.Parse(Console.ReadLine());
Num1 = a;
Num2 = b;
while (Num2 != 0)
{
temp = Num2;
Num2 = Num1 % Num2;
Num1 = temp;
}
GCD = Num1;
LCM = (a * b) / GCD;
Console.WriteLine("LCM for {0} and {1} is {2}", a, b, LCM);
Console.WriteLine("GCD for {0} and {1} is {2}", a, b, GCD);
===================================================================================
==================================
// PROGRAM TO PRINT CHARACTERS LIKE BELOW?
int count = 0;
for (char c = 'A'; c <= 'Z'; c++)
{
count++;
for (int i = 0; i < count; i++)
{
Console.Write(c);
}
Console.WriteLine();
}
output:-
--------
A
BB
CCC
DDDD
-----
------
YYYYYYYYYYYYYYYYYYYYYYYYY
ZZZZZZZZZZZZZZZZZZZZZZZZZZ
===================================================================================
==================================
Q) Find nth Highest salary using LINQ?
List<Student> studentList = new List<Student>() {
new Student() { StudentID = 1, StudentName = "John", Age = 18 ,Salary=20000} ,
new Student() { StudentID = 2, StudentName = "Steve", Age =
15,Salary=30000 } ,
new Student() { StudentID = 3, StudentName = "Bill", Age = 25 ,Salary=40000} ,
new Student() { StudentID = 4, StudentName = "Ram" , Age = 20 ,Salary=50000} ,
new Student() { StudentID = 5, StudentName = "Ron" , Age = 19 ,Salary=60000}
};
var nthHighestSalary = studentList.OrderByDescending(s =>
s.Salary).Skip(2).First();
(OR)
var nthHighestSalary = studentList.GroupBy(e =>
e.Salary).OrderByDescending(g => g.Key).Skip(1).First();
====================================================COMPLETED======================
==================================

===================================================================================
==================================
WCF:-
=====

Q) What is WCF?
WCF stands for Windows Communication Foundation and is part of .NET 3.0. WCF is
Microsoft platform for building distributed and interoperable applications.
===================================================================================
==================================
Q) What is a distributed application?
In simple terms a distributed application, is an application where parts of it run
on 2 or more computers. Distributed applications are also called as connected
systems or applications.

Examples:
A web application running on one machine and a web service that this application is
consuming is running on another machine.
An enterprise web application may have the following tiers, and each tier may be
running on a different machine
1. Presentation tier
2. Business tier
3. Data Access tier
===================================================================================
==================================
Q) Why build distributed applications?
There are several reasons for this
1. An enterprise application may need to use the services provided by other
enterprises. For example an ecommerce application may be using paypal service for
payments.
2. For better scalability. An enterprise web application may have Presentation
tier, Business tier, and Data Access tiert, and each tier may be running on a
different machine.
===================================================================================
==================================
Q) What is an interoperable application?
An application that can communicate with any other application that is built on any
platform and using any programming language is called as an interoperable
application. Web services are interoperable, where as .NET remoting services are
not. Web services can communicate with any application built on any platform, where
as a .NET remoting service can be consumed only by a .net application.
===================================================================================
==================================
Q) What technology choices did we have before WCF to build distributed
applications?
Enterprise Services
Dot Net Remoting
Web Services
===================================================================================
==================================
Q) Why should we use WCF?
Let's take this scenario
We have 2 clients and we need to implement a service a for them.
1. The first client is using a Java application to interact with our service, so
for interoperability this client wants messages to be in XML format and the
protocol to be HTTP.
2. The second client uses .NET, so for better performance this client wants
messages formmated in binary over TCP protocol.

Without WCF
1. To satisfy the first client requirement we end up implementing an ASMX web
service, and
2. To satisfy the second client requirement we end up implementing a remoting
service

These are 2 different technologies, and have complete different programming models.
So the developers have to learn different technologies.

So to unify and bring all these technologies under one roof Microsoft has come up
with a single programming model that is called as WCF - Windows Communication
Foundation.

With WCF,
You implement one service and we can configure as many end points as want to
support all the client needs. To support the above 2 client requirements, we would
configure 2 end points. In the endpoint configuration we can specify the protocols
and message formats that we want to use.
===================================================================================
==================================
Q) How to make changes to wcf service without breaking clients?
Use Name property of ServiceContractAttribute and give it an explicit name to
prevent the clients from breaking when you change the service contract interface
name.

We have not used Name property of the ServiceContractAttribute in the example


below.
[ServiceContract]
public interface IHelloService
{ [OperationContract] string GetMessage(string name);
}

Later if we change the interface name from IHelloService to IHelloServiceChanged,


this would break the existing clients consuming your wcf service. In order to
prevent this from happening use Name property as shown below.
[ServiceContract(Name = "IHelloService")]
public interface IHelloServiceChanged
{ [OperationContract] string GetMessage(string name);
}

In WSDL document, we have something called portType. You can think of this portType
as the interface the client uses to communicate with the wcf service. When you
don't set the Name property on a service contract attribute, by default the name of
the portType in WSDL will be the name of the service contract interface. If you set
an explicit Name for the service contract using Name property then that Name will
be used for the portType.
In a similar fashion you can set Name property for an OperationContract as shown
below.
[ServiceContract(Name = "IHelloService")]
public interface IHelloServiceChanged
{ [OperationContract(Name = "GetMessage")] string GetMessageChanged(string name);
}
===================================================================================
==================================
Q) DataContract and DataMember in WCF?
To understand DataContract and DataMember attributes in WCF, first let's understand
what is meant by Serialization.

With respect to WCF, Serialization is the process of converting an object into an


XML representation. The reverse process, that is reconstructing the same object
from the XML is called as Deserialization.

By default, WCF uses DataContractSerializer.


For a complex type like Customer, Employee, Student to be serialized, the complex
type can either be decorated with
1. SerializableAttribute or
2. DataContractAttribute

With .NET 3.5 SP1 and above, we don't have to explicitly use DataContract or
DataMember attributes. The Data Contract Serializer will serialize all public
properties of your complex type in an alphabetical order. By default private field
and properties are not serialized.

If we decorate a complex type, with [Serializable] attribute the


DataContractSerializer serializes all fields. With [Serializable] attribute we
don't have explicit control on what fields to include and exclude in serialized
data.

If we decorate a complex type with [Datacontract] attribute, the


DataContractSerializer serializes the fields marked with the [DataMember]
attribute. The fields that are not marked with [DataMember] attribute are excluded
from serialization. The [DataMember] attribute can be applied either on the private
fields or public properties.

In WCF, the most common way of serialization is to mark the type with the
DataContract attribute and mark each member that needs to be serialized with the
DataMember attribute.

If you want to have explicit control on what fields and properties get serialized
then use DataContract and DataMember attributes. 1. Using DataContractAttribute,
you can define an XML namespace for your data
2. Using DataMemberAttribute, you can a) Define Name, Order, and whether if a
property or field IsRequired b) Also, serialize private fields and properties
===================================================================================
==================================
Q) Different ways of associating known types in wcf?
There are 4 different ways to associate KnownTypes
1. Use KnownType attribute on the base type. This option is global, that is all
service contracts and all operation contracts will respect the known types.
[KnownType(typeof(FullTimeEmployee))]
[KnownType(typeof(PartTimeEmployee))]
[DataContract]
public class Employee
{
}

[DataContract]
public class FullTimeEmployee : Employee
{ public int AnnualSalary { get; set; }
}

[DataContract]
public class PartTimeEmployee : Employee
{ public int HourlyPay { get; set; } public int HoursWorked { get; set; }
}

2. Apply ServiceKnownType attribute on the service contract. With this option the
known types are respected by all operation contracts with in this service contract
only.
[ServiceKnownType(typeof(PartTimeEmployee))]
[ServiceKnownType(typeof(FullTimeEmployee))]
[ServiceContract]
public interface IEmployeeService
{ [OperationContract] Employee GetEmployee(int Id); [OperationContract] void
SaveEmployee(Employee Employee);
}

3. If you want even more granular control, then apply ServiceKnownType attribute on
specific operation contracts. With this option, only the operation contracts that
are decorated with ServiceKnownType attribute respect known types.
[ServiceContract]
public interface IEmployeeService
{ [ServiceKnownType(typeof(PartTimeEmployee))]
[ServiceKnownType(typeof(FullTimeEmployee))] [OperationContract] Employee
GetEmployee(int Id); [OperationContract] void SaveEmployee(Employee Employee);
}

4. You can also specify known types in the configuration file. This is equivalent
to applying KnownType attribute on the base type, in the sense that it is
applicable globally. All service contracts and operation contracts respect the
known types.
===================================================================================
==================================
Q) How to enable tracing and message logging in wcf?
Use Microsoft Service Configuration Editor to enable tracing and message logging in
WCF. This can be done either on the client or the wcf service.

Enable Tracing and Message Logging in WCF


1. Right click on the config file and select "Edit WCF Configuration" option from
the context menu. If you don't see this option, click on Tools menu item and then
selecct WCF Configuration Editor and then point to the config file.
2. Select Diagnostics folder
3. Click on Enable Log Auto Flush link.
4. Then click on Enable Message Logging link. This should automatically add file,
to which messages will be logged. To enable tracing click on Enable Tracing link.
5. Expand Diagnostics folder on the left hand side
6. Select Message Logging item that is present under Diagnostics folder. On the
right hand side set LogEntireMessage option to true.
7. Close Microsoft Service Configuration Editor tool. This will ask you to Save
Changes. Click Yes.

The config file should updated with the settings we have made using the tool. At
this point we have enabled tracing and message logging.
Run the wcf service and the client. Make a request from the client. Look for the
log files in the client or service folder depending on where you have enabled
tracing and message logging.

To open the log files use Service Trace Viewer utility that ships with .NET. To
open Service Trace Viewer utility, there are 2 options
1. Click on Start
2. Click All Programs.
3. Open Microsoft Visual Studio 2010 folder
4. Open Windows SDK Tools folder and then select Service Trace Viewer tool

Open Service Trace Viewer from visual studio command prompt


1. Open visual studio command prompt
2. Type SVCTRACEVIEWER and press enter

Point the Service Trace Viewer utility to the log file and you should see the
messages exchanged between the service and the client.
===================================================================================
==================================
Q) Message Contract in WCF?
With Data Contracts we have very limited control over the SOAP XML messages that
are generated. Use Message Contracts, if you want to have full control over the
generated XML SOAP messages.

Few examples of when Message Contracts can be handy


1. Include some custom data in the SOAP header. In general SOAP headers are used to
pass user credentials, license keys, session keys etc.
2. Change the name of the wrapper element in the SOAP message or to remove it
altogether.

In this demo, we will discuss how to use MessageContracts


1. To include LicenseKey in the SOAP Header
2. Change the Name of the wrapper element in the SOAP Body

Decorate a class with MessageContract attribute, and then use that class as an
operation contract parameter or return type. MessageContract attribute has the
following parameters.
1. IsWrapped
2. WrapperName
3. WrapperNamespace
4. ProtectionLevel

MessageHeader attribute is applied on a property of the class that you want to


include in the SOAP header. MessageHeader attribute has the following parameters.
1. Name
2. Namespace
3. ProtectionLevel
4. Actor
5. MustUnderstand
6. Relay

MessageBodyMember attribute is applied on a property of the class that you want to


include in the SOAP body section. MessageBodyMember attribute has the following
parameters.
1. Name
2. Namespace
3. Order
4. ProtectionLevel
In general, use MessageContract only if there is a reason to tweak the structure of
the soap XML message.
===================================================================================
==================================
Q) Difference between datacontract and messagecontract in wcf?
DataContract gives very limited control over the SOAP messages. DataContract allows
us to control the Name and Order of XML elements in the body section of the SOAP
message. Beyond this we don't have much control over the SOAP messages.

On the other hand, MessageContract gives full control over the SOAP messages by
providing access to the SOAP header and body sections using MessageHeader and
MessageBodyMember attributes. Use MessageContract if there is a reason to tweak the
structure of the soap XML i.e if you want to include any additional information in
the SOAP header.

1. Why do use MessageContract in WCF?


MessageContract gives full control over the SOAP messages. For example, it allows
us to include custom information in the SOAP header.

2. What kind of custom information?


User credentials to invoke the service

3. Why do you need to pass user credentials in the header? Can't you pass them as
method parameters?
We can, but user credentials are periphery to what the method has to do. So, it
would make more sense to pass them out of band in the header, rather than as
additional parameters.

4. SOAP messages are in xml format, so anyone can read the credentials? How you do
you protect sensitive data?
Using MessageContract we can sign and encrypt messages. Use ProtectionLevel named
parameter.
===================================================================================
==================================
Q) Backward compatible WCF contract changes?
After a WCF service is deployed on the production server, the WSDL document should
not be changed in any way that would break the existing clients. This is because
the clients have already generated proxy classes and relevant configuration to
interact with the service. If you intend to make changes, the changes should be
done in such a way that they support backward compatibility.

WCF contracts are version tolerant by default. The DataContractSerializer which is


the default engine for serialization in WCF allows missing, non-required data and
ignores superfluous data for service contracts, data contracts & message contracts.

If you remove the existing operation contracts, the service would throw an
exception if they try to invoke that missing operation contract.
[ServiceContract]
public interface IEmployeeService
{ [OperationContract] Employee GetEmployee(int Id); //[OperationContract] //void
SaveEmployee(Employee Employee);
}

If you add a new operation contract, the existing clients will not know about the
new method and would continue to work in the same way as before.
[ServiceContract]
public interface IEmployeeService
{ [OperationContract] Employee GetEmployee(int Id); [OperationContract] void
SaveEmployee(Employee Employee); [OperationContract] string GetEmployeeNameById(int
Id);
}

For example, removing Gender property which is not required from the DataContract
will not break the existing clients. The existing clients will continue to send
data for Gender property to the service. At the service side, Gender property value
will simply be ignored.
[DataContract(Namespace = "http://pragimtech.com/Employee")]
public class Employee
{ [DataMember(Order = 1)] public int Id { get; set; } [DataMember(Order = 2)]
public string Name { get; set; } //[DataMember(Order = 3)] //public string Gender {
get; set; } [DataMember(Order = 4)] public DateTime DateOfBirth { get; set; }
[DataMember(Order = 5)] public EmployeeType Type { get; set; }
}

Along the same lines if a new non required field City is added, the existing
clients will not send data for this field, and the service WILL NOT throw an
exception as it is not a required field.
[DataContract(Namespace = "http://pragimtech.com/Employee")]
public class Employee
{ [DataMember(Order = 1)] public int Id { get; set; } [DataMember(Order = 2)]
public string Name { get; set; } //[DataMember(Order = 3)] //public string Gender {
get; set; } [DataMember(Order = 4)] public DateTime DateOfBirth { get; set; }
[DataMember(Order = 5)] public EmployeeType Type { get; set; } [DataMember(Order =
6)] public string City { get; set; }
}

On the other hand, if you make it a required field, the service would throw an
exception.

For a full list of changes and the impact that could have on the existing clients,
please refer to the following MSDN article
https://msdn.microsoft.com/en-us/library/ff384251.aspx
===================================================================================
==================================
Q) Exception handling in WCF?
When an exception occurs in a WCF service, the service serializes the exception
into a SOAP fault, and then sends the SOAP fault to the client.

By default unhandled exception details are not included in SOAP faults that are
propagated to client applications for security reasons. Instead a generic SOAP
fault is returned to the client.

For debugging purpose, if you want to include exception details in SOAP faults,
enable IncludeExceptionDetailInFaults setting. This can be done in 2 ways as shown
below.
1. In the config file using service behavior configuration
[behaviors]
[serviceBehaviors] [behavior name="inculdeExceptionDetails"] [serviceDebug
includeExceptionDetailInFaults="true"/] [/behavior]
[/serviceBehaviors]
[/behaviors]

2. In code using ServiceBehavior attribute


[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class CalculatorService : ICalculatorService
{ public int Divide(int Numerator, int Denominator) { return Numerator /
Denominator; }
}

Frequently asked WCF interview questions


What happens when an exception occurs in a WCF service?
OR
What is a SOAP fault?
OR
How are WCF service exceptions reported to client applications?
===================================================================================
==================================
Q) Soap faults in WCF?
WCF serializes exceptions to SOAP faults before reporting the exception information
to the client. This is because exceptions are not allowed to be passed through a
wcf service channel.

SOAP faults are in XML format and are platform independent. A typical SOAP fault
contains
1. FaultCode
2. FaultReason
3. Detail elements etc.

The Detail element can be used to include any custom xml. We will discuss more
about Detail element in a later video session.

SOAP faults are formatted based on SOAP 1.1 or SOAP 1.2 speficications. SOAP format
depends on the binding. BasicHttpBinding uses SOAP 1.1 whereas the other built-in
WCF bindings use SOAP 1.2.

To view SOAP 1.1 fault message, set binding to basicHttpBinding. To view SOAP 1.2
fault message, set binding to wsHttpBinding. By default Message Security is turned
on for wsHttpBinding. Set the security mode for wsHttpBinding to None, so we could
view the SOAP 1.2 fault message.
===================================================================================
==================================
Q) Bindings in WCF?
A endpoint is where the service is available for the clients of the service to be
consume.

A WCF service endpoint consists of 3 things


A -Address (Address where the WCF Service is available)
B -Binding (We will discuss this in more detail in this video)
C - Contract (Specifies what the service can do. For example, the service contract
describes which operations the client can perform on the service)

So, what is a binding in a WCF service?


A WCF binding defines how the client needs to communicate with the service. The WCF
binding that you choose determines the following for the communication between the
client and the service.
Transport Protocol (for example, HTTP, TCP, NamedPipe, MSMQ)
Message Encoding (for example, text/XML, binary, or (MTOM) Message Transmission
Optimization Mechanism)
Protocols (for example, reliable messaging, transaction support)

In WCF there are several built-in bindings that we could use. The complete list can
be found at the following MSDN link
https://msdn.microsoft.com/en-us/library/ms730879(v=vs.110).aspx

Depending on your application requirement, you pick the binding that best suit your
needs. If you are not sure, which binding to use there is a flowchart at the
following link that can be handy.
http://stackoverflow.com/questions/10849920/different-wcf-bindings-their-
differences-and-compatibility-with-other-platforms

As WCF is very extensible, you can also create a custom binding and use it, if none
of the system provided bindings suit your needs.
===================================================================================
==================================
Q) Message Exchange Patterns that are available in WCF?
We know that WCF keeps data in XML or JSON format. When a client sends a request to
a service and the service sends a response to the client then the request and
response is in XML or JSON format, in other words the message exchange is in the
format of XML or JSON between the client and the service.

Message Exchange Pattern describes how the client and the wcf service exchange
messages. WCF supports the following 3 Message Exchange Patterns. The default
Message Exchange Pattern in WCF is Request-Reply.

1. Request-Reply (Default)
2. One-Way
3. Duplex

Request-Reply:
1. This is the default Message Exchange Pattern
2. Client sends a message to a WCF Service and then waits for a reply. During this
time the client client stops processing until a response is received from the wcf
service.
3. The client waits for the service call to complete even if the operation return
type is void.
4. All WCF bindings except the MSMQ-based bindings support the Request-Reply
Message Exchange Pattern.
5. IsOneWay parameter of OperationContract attribute specifies the Message Exchange
Pattern. The default value for IsOneWay parameter is false. This means that, if we
don't specify this parameter, then the Message Exchange Pattern is Request/Reply.
So the following 2 declarations are equivalent.

[ServiceContract]
public interface ISampleService
{
[OperationContract(IsOneWay=false)]
string RequestReplyOperation();

[OperationContract(IsOneWay = false)]
string RequestReplyOperation_ThrowsException();
}

OR

[ServiceContract]
public interface ISampleService
{
[OperationContract]
string RequestReplyOperation();

[OperationContract] string RequestReplyOperation_ThrowsException();


}

6. In a Request-Reply message exchange pattern faults and exceptions get reported


to the client immediately if any.
The advantages of request/response message pattern is:
------------------------------------------------------
-> Supports all the bindings except MSMQ-based binding
-> If an exception occurrs in the service then it immediately informs the client
and developer so the developer can easily get the faults in the service.

The disadvantages of the request/response pattern is:


-----------------------------------------------------
-> The client must wait more time since there is so much processing before the
service can send the TimeoutException to the client
===================================================================================
==================================
Q) OneWay Message Exchange Pattern in WCF?
In a Request-Reply pattern, the client sends a message to the WCF service and then
waits for the reply message, even if the service operation's return type is void.

In case of One-Way operation, only one message is exchanged between the client and
the service. The client makes a call to the service method, but does not wait for a
response message. So, in short, the receiver of the message does not send a reply
message, nor does the sender of the message expects one.

As messages are exchanged only in one way, faults if any while processing the
request does not get reported.

Clients are unaware of the server channel faults until a subsequent call is made.

An exception will be thrown, if operations marked with IsOneWay=true declares


output parameters, by-reference parameters or return value.

Are OneWay calls same as asynchronous calls?


No, they are not. When a oneway call is received at the service, and if the service
is busy serving other requests, then the call gets queued and the client is
unblocked and can continue executing while the service processes the operation in
the background. One-way calls can still block the client, if the number of messages
waiting to be processed has exceeded the server queue limit. So, OneWay calls are
not asynchronous calls, they just appear to be asynchronous.

To make an operation one-way, set IsOneWay=true.


[OperationContract(IsOneWay=true)]
void OneWayOperation();

[OperationContract(IsOneWay = true)]
void OneWayOperation_ThrowsException();

Service Implementation:
public void OneWayOperation()
{ Thread.Sleep(2000); return;
}

public void OneWayOperation_ThrowsException()


{ throw new NotImplementedException();
}

The following are the advantages of OneWay:


-------------------------------------------
=> Clients are unaware of any exceptions of the service.
=> It takes less time for the process
=> the client is not blocked after a request, the client can do his other work.
=> This pattern is doing work like asynchronous

The following are the disadvantages of OneWay:


----------------------------------------------
=> If the request exceeds the limit of the queue then it can be blocked by the
client.
=> The client cannot know whether or not the request is reached successfully
===================================================================================
==================================
Q) Difference between WCF and ASP.NET Web Service?
WCF:-
-----
=> ServiceContract and OperationContract attributes are used for defining WCF
service.
=> Supports various protocols like HTTP, HTTPS, TCP, Named Pipes and MSMQ.
=> Hosted in IIS, WAS (Windows Activation Service), Self-hosting, Windows Service.
=> Supports security, reliable messaging, transaction and AJAX and REST supports.
=> Supports DataContract serializer by using System.Runtime.Serialization.
=> Supports One-Way, Request-Response and Duplex service operations.
=> WCF are faster than Web Services.
=> Hash Table can be serialized.
=> Unhandled Exceptions does not return to the client as SOAP faults. WCF supports
better exception handling by using FaultContract.
=> Supports XML, MTOM, Binary message encoding.
=> Supports multi-threading by using ServiceBehaviour class.

ASP.NET Web Service:-


----------------------
=> WebService and WebMethod attributes are used for defining web service.
=> Supports only HTTP, HTTPS protocols.
=> Hosted only in IIS.
=> Support security but is less secure as compared to WCF.
=> Supports XML serializer by using System.Xml.Serialization.
=> Supports One-Way and Request-Response service operations.
=> Web Services are slower than WCF
=> Hash Table cannot be serialized. It can serializes only those collections which
implement IEnumerable and ICollection.
=> Unhandled Exceptions returns to the client as SOAP faults.
=> Supports XML and MTOM (Message Transmission Optimization Mechanism) message
encoding.
=> Doesn�t support multi-threading.
===================================================================================
==================================
Q) What is Proxy and how to generate proxy for WCF Services?Difference between WCF
Proxy and Channel Factory
There are two ways : Proxy and Channel Factory; to create a WCF Client or calling a
WCF Service. In this article, I am going to expose the difference between Proxy and
Channel Factory.

WCF Proxy:
----------
A WCF proxy is a CLR class that exposes the service contract. A Service proxy class
has the service contract operations and some additional operations for managing the
proxy life cycle and the connection to the service.

There are two ways to create a WCF proxy as given below:


=> Using Visual Studio by adding service reference to the client application.
=> Using SvcUtil.exe command-line utility.
Channel Factory:
----------------
A channel factory creates channels of different types that are used by client to
send messages to the service. ChannelFactory class is used with a known interface
to create the channel. This approach is commonly used when you have access control
to both the server and the client.

WSHttpBinding binding = new WSHttpBinding();


EndpointAddress endpoint = new
EndpointAddress("http://localhost/WcfService/MyService.svc/ws");

ChannelFactory<IMyService>channelFactory = new
ChannelFactory<IMyService>(binding,endpoint );
IMyService channel = channelFactory.CreateChannel();

//calling service operation


channel.DoWork();

//Close channel
channelFactory.Close();

Difference between WCF Proxy and Channel Factory:


-------------------------------------------------
Proxy:
------
=> Only requires the service URL to access the service.
=> Simple and easy to understand
=> Proxy is best when your service is used by several applications.
=> Proxy can be created by using Visual Studio or SVCUtil tool.

Channel Factory:-
-----------------
=> Requires direct access to the assembly which contains the service contract i.e.
must have information about service interface.
=> Not easy since channels are complex and network-related
=> Channel Factory is best when your service is tightly bound to a single
application
=> ChannelFactory class is used to create channel and for accessing the service.
=================================================COMPLETED=========================
==================================

===================================================================================
==================================
OTHER TOPICS:-
--------------
SDLC Process:-
-> Requirement Gathering
-> Design
-> Development
-> Testing
-> Maintaince

AngularJS :-
------------
http://www.c-sharpcorner.com/article/top-50-angularjs-interview-questions-and-
answers
https://www.codeproject.com/Articles/891718/AngularJS-Interview-Questions-and-
Answers

ASP.NET MVC :-
--------------
https://www.codeproject.com/Articles/556995/ASP-NET-MVC-interview-questions-with-
answers

WCF :-
-------
https://www.codeproject.com/Articles/759331/Interview-Questions-Answers-Windows-
Communication
http://www.c-sharpcorner.com/UploadFile/8ef97c/wcf-interview-questions-and-answers
https://www.questpond.com/dotnet/WCF-Interview-Questions-and-Answers.html
=================================================COMPLETED=========================
==================================

===================================================================================
==================================
JavaScript & Jquery:-
---------------------
Q) How to get the checkbox value in jquery using serializearray?
/* Get input values from form */
values = jQuery("#myform").serializeArray();

/* Because serializeArray() ignores unset checkboxes and radio buttons: */


values = values.concat(
jQuery('#myform input[type=checkbox]:not(:checked)').map(
function() {
return {"name": this.name, "value": this.value}
}).get()
);
===================================================================================
==================================
Q) Get the contents of a table row with a button click in Jquery?
Sample Table:-
--------------
<table id="choose-address-table" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name/Nr.</th>
<th>Street</th>
<th>Town</th>
<th>Postcode</th>
<th>Country</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td class="nr"><span>50</span>
</td>
<td>Some Street 1</td>
<td>Glasgow</td>
<td>G0 0XX</td>
<td>United Kingdom</td>
<td>
<button type="button" class="use-address" />
</td>
</tr>
<tr>
<td class="nr">49</td>
<td>Some Street 2</td>
<td>Glasgow</td>
<td>G0 0XX</td>
<td>United Kingdom</td>
<td>
<button type="button" class="use-address" />
</td>
</tr>
</tbody>
</table>

For Html Tables:-


-----------------
var tblElements= [];
$(".use-address").click(function() {
var $row = $(this).closest("tr"); // Find the row
var $tds = $row.find("td");
$.each($tds, function() {
tblElements.push($(this).text());
});

});

For Data Tables:-


-----------------
$(document).ready(function () {
var table = $('#users').DataTable();
$('#users tbody').on('click', 'tr', function () {
console.log(table.row(this).data());
});
});
===================================================================================
==================================
Q) How to get the values from different input controls using jquery?
TextBox:-
---------
$("#txtEmail").val()

You can also use the val(string) method to set that value:
$("#txtEmail").val("something")

Dropdown List:-
---------------
For single select dom elements, to get the currently selected value:
$('#dropDownId').val();

To get the currently selected text:


$('#dropDownId :selected').text();
CheckBox:-
----------
To get the value of the Value attribute you can do something like this:
$("input[type='checkbox']").val();

Or if you have set a class or id for it, you can:


$('#check_id').val();
$('.check_class').val();

RadioButton:-
-------------
$('input[name=name_of_your_radiobutton]:checked').val();
===================================================================================
==================================
Q) What is the difference between �==� and �===�?
Ans:
�==� checks equality only,
�===� checks for equality as well as the type.

Example:-
---------
Using the == operator (Equality)
---------------------------------
true == 1; //true, because 'true' is converted to 1 and then compared
"2" == 2; //true, because "2" is converted to 2 and then compared

Using the === operator (Identity)


---------------------------------
true === 1; //false
"2" === 2; //false

=>This is because the equality operator == does type coercion, meaning that the
interpreter implicitly tries to convert the values before comparing.
=>On the other hand, the identity operator === does not do type coercion, and thus
does not convert the values when comparing.
===================================================================================
==================================
Q) What does isNaN function do?
Ans: It returns true if the argument is not a number.

Example:
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2013/06/23")+ "<br>");
document.write(isNaN(123)+ "<br>");

The output will be:


true
true
false
===================================================================================
==================================
What is Manual Testing ?
Manual Testing is a process of finding out the defects or bugs in a software
program. In this method the tester plays an important role of end user and verifies
that all the features of the application are working correctly. The tester manually
executes test cases without using any automation tools. The tester prepares a test
plan document which describes the detailed and systematic approach to testing of
software applications. Test cases are planned to cover almost 100% of the software
application. As manual testing involves complete test cases it is a time consuming
test.

The differences between actual and desired results are treated as defects. The
defects are then fixed by the developer of software application. The tester retests
the defects to ensure that defects are fixed. The goal of Manual testing is to
ensure that application is defect & error free and is working fine to provide good
quality work to customers.
===================================================================================
==================================