NET Interview Questions & Answers
NET Interview Questions & Answers
-> A class is a constructs that enables you to create your own custom types by
grouping together variables of other types, methods and events.
class Program
{
static void Main(string[] args)
{
Customer objCustomer = new Customer();
objCustomer.customerNo = "10001";
objCustomer.customerName = "Rakesh";
->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
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.
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;
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;
}
class TestPerson
{
static void Main()
{
// Create a Person object by using the instance constructor.
Person person1 = new Person("George", 40);
// Show details to verify that the name and age fields are distinct.
Console.WriteLine(person1.Details());
Console.WriteLine(person2.Details());
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;
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.
class TestCounter
{
static void Main()
{
Counter.currentCount = 100;
Counter.IncrementCount();
Console.WriteLine("New count: {0}", Counter.currentCount);
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.
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 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".
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();
}
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 Program
{
static void Main(string[] args)
{
Console.WriteLine("//////////////////// - Interface Demo
- //////////////////// \n");
IDriveable DriveCar = new Car();
IDriveable DriveTruck = new Truck();
using System;
namespace InterfaceDemo
{
//First Interface IDebitCard
interface IDebitCard
{
void CardNumber();
}
}
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;
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
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).
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.
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.
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;
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
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;
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
}
/* Output
1
2
*/
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.
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 {}
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.
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.
--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.
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.
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 };
Console.WriteLine();
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.
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.
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:
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][];
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.
Example:-
---------
Public class BaseClass
{
public string GetMethodOwnerName()
{
return "Base Class";
}
}
public class ChildClass : BaseClass
{
public new string GetMethodOwnerName()
{
return "ChildClass";
}
}
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.
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.
Example:-
--------
public class NormalClass
{
public void Display()
{
Console.WriteLine("I m in Display");
}
public void Print()
{
Console.WriteLine("I m in Print");
}
}
//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
}
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);
}
}
Employee.PromoteEmployee(emplist,del);
}
class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public int Salary { get; set; }
public int Experience { get; set; }
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();
//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:
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();
}
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.
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;
}
}
}
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:
IList, IList<T> You want to modify the collection and you care
about the ordering and / or positioning of the
elements in the collection.
int i = 10;
Int32 j = 10;
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
}
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.
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.
double factorial = 1;
using System.IO;
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; }
}
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.
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.
class Database
{
public void AddRow(string Table, string Value)
{
}
}
interface IDatabase
{
void AddRow(string Table, string Value);
}
Console.WriteLine(z1);
}
}
//output:
6
===================================================================================
==================================
ADO.NET:
========
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();
}
}
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.
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.
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();
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.
Now create a procedure to receive data for the Table Valued Parameter and insert it
into our original table:
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:
//Create Table
DataTable myTable = CreateTable();
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:
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
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"));
}
}
return 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
USE USADB
GO
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
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')
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);
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>
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.
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.
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.
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.
===================================================================================
==================================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.
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.
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.
->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.
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.
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.
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
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 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.
<sessionState mode="SQLServer"
cookieless="true "
regenerateExpiredSessionId="true "
timeout="30"
sqlConnectionString="Data Source=MySqlServer;Integrated Security=SSPI;"
stateNetworkTimeout="30"/>
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....
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.
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.
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:
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.
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.
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.
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.
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.
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>
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>
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>
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="[email protected]"/>
</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.
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
===================================================================================
==================================
ASP.NET MVC:
============
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.
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.
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.
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.
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.
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.
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:
[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.
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)
{
}
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.
=>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.
=> 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.
=> 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.
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.
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"];
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.
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.
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.
=> 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
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.
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; }
<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.
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
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.
<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();
}
Parameter Description
[OutputCache(Duration=3600,Location=System.Web.UI.OutputCacheLocation.None)]
<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".
[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();
}
@{
ViewBag.Title = "MyProfile";
}
<h2>MyProfile</h2>
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" })
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");
}
[HttpPost]
public ActionResult Index(string Name)
{
ViewBag.Message = "Hi, Dot Net Tricks";
//Like Server.Transfer() in Asp.Net WebForm
return 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");
}
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");
}
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
[HttpPost]
public ActionResult Index(string Name)
{
return RedirectToRoute("MyRoute");
}
AccountController
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.
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.
[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:-
--------
["Students Name", "N/A", "N/A", "0", "0", "Yes", "Cash/Credit", prevObject:
init[1], context: document]
(OR)
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.
===================================================================================
==================================
LINQ:
=====
===================================================================================
==================================
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 }
};
OfType:-
=======
var stringResult = mixedList.OfType<string>();
output:
-------
One
Two
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
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
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
});
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 }
};
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 }
};
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 }
};
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.
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.
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.
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.
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.
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.
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.
Output:
-------
true
Concatenation Operator:
-----------------------
Concat:-
========
The Concat() method appends two sequences of the same type and returns a new
sequence (collection).
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.
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.
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)
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
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:
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.
>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.
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.
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
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.
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
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;
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;
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;
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 : MIN()
SELECT MAX(rate)
FROM product_mast;
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.
->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 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
Dropping a View:
----------------
Drop View Employee_View1
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.
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.
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
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.'
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.
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.
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-
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
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:
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.
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.
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
);
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.
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.
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.
--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.
--OPEN CURSOR.
OPEN PrintCustomers
--INCREMENT COUNTER.
SET @Counter = @Counter + 1
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)
WITH EmployeeCTE AS
(
Select EmployeeId, EmployeeName, ManagerID
From Employees
Where EmployeeId = @ID
UNION ALL
-> LEFT JOIN returns all rows from left table including non-matching rows.
In this case we use RIGHT JOIN To retrieve all Department and Employee names,
irrespective of whether a Department has Employees or not.
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.
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.
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)
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
-- Transaction 2
Begin Tran
Update TableB Set Name = 'Mark Transaction 2' where Id = 1
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.
Syntax:-
---------
Select * from table_1 as t1
right outer join table_2 as t2
on t1.IDcol=t2.IDcol
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.
Benefits :-
-----------
-> Eliminate data redundancy
-> Improve performance
-> Query optimization
-> Faster update due to less number of columns in one table
-> Index improvement
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.
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;
--Show data
SELECT * FROM @Employee
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;
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
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 };
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?
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);
}
===================================================================================
==================================
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.
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 .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.
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.
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
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.
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
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.
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.
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]
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.
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();
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.
[OperationContract(IsOneWay = true)]
void OneWayOperation_ThrowsException();
Service Implementation:
public void OneWayOperation()
{ Thread.Sleep(2000); return;
}
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.
ChannelFactory<IMyService>channelFactory = new
ChannelFactory<IMyService>(binding,endpoint );
IMyService channel = channelFactory.CreateChannel();
//Close channel
channelFactory.Close();
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();
});
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();
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
=>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 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.
===================================================================================
==================================