Vous êtes sur la page 1sur 71

Contents

1. How the Encapsulation is different from Abstraction? I think both are used to hide the
unnecessary details? Then how they are different?......................................................................5
2. What do you mean by early binding and late binding in the object bindings? Which is
good? Please give me a scenario where you have used the early binding and late binding
concepts in your application?.............................................................................................................7
3. In garbage collection, how the object generations come in the picture? How many
generations an object can have? Please tell me the process of disposing the objects
based on the generations? Can an object move from one generation to another? If yes
then why? What’s the need to have different generations as we are going to dispose the
objects which are marked by the Garbage collector? Ans...........................................................8
4. What is object graph in garbage collector? Is this the graph physically exists? Or how
this graph gets created?.......................................................................................................................9
5. Can we suppress the Garbage collector? If yes, then why do we need to suppress it as
it is used to reclaim the unused memory and which improve s the performance of our
application?...........................................................................................................................................10
6. We already have the Finalize method which reclaims the memory using the Garbage
collector. This is automatic process then why do we have the Dispose () method? Is this
method different from Finalize ()? What is the interface from which the Dispose () method
inherited?................................................................................................................................................10
20. Why we used Inheritance. What is the benefit of this...........................................................11
21. Why C# does not support Multiple Inheritance......................................................................11
22. Why we used virtual keyword.....................................................................................................12
24. What are events and actions in c#.............................................................................................13
29. Why we use Interface....................................................................................................................13
30. Why we use Method Overloading..............................................................................................14
31. Why we use Method Overriding.................................................................................................14
33. In which case we can use Abstract class in our project......................................................14
34. What is the difference between Array List and Ilist...............................................................14
35. What is difference between internal class and sealed class...............................................15
37. What is the difference between Remoting and web service................................................15
40. What is type safety in .NET?.......................................................................................................15
50. What are static classes.................................................................................................................15
51. When are static classes initialized.............................................................................................15
52. What is difference between static class and singleton class.............................................16
53. Is it possible to have a static constructor in class. If yes why do we need to have a
static constructor.................................................................................................................................16

1|Page
54. What are delegates........................................................................................................................16
55. What is a multicast delegate.......................................................................................................16
56. How can we achieve asynchronous programming using delegates.................................16
57. Are delegates type safe................................................................................................................17
58. What is the difference between Convert.ToSting() and Object.ToSting() instance
method of a class.................................................................................................................................17
63. What is C#?.....................................................................................................................................17
68. Define Constructors?....................................................................................................................17
71. What is the use of using statement in C#?..............................................................................17
72. What is serialization?....................................................................................................................17
74. What is difference between constants and read-only?........................................................17
78. What are sealed classes in C#?..................................................................................................17
83. What are the differences between System.String and System.Text.StringBuilder
classes?..................................................................................................................................................18
84. What’s the difference between the System.Array.CopyTo() and System.Array.Clone() ?
.................................................................................................................................................................. 18
88. What is the difference between Finalize() and Dispose() methods?.................................18
90. What are generics in C#.NET?....................................................................................................18
91. What is an object pool in .NET?.................................................................................................18
102. What is the difference between a Struct and a Class?.......................................................18
105. What is difference between is and as operators in c#?......................................................18
107. What are indexers in C# .NET?.................................................................................................19
1) What is store procedure? How do they work? When do you use?.....................................19
2) SQL Server Functions,Types and Examples.............................................................................19
3) What is SQL view? Why use View instead of a Table? Advantages and Drawbacks......20
4) What is Index? How do database indexes work? How do indexes help, Types?.............21
5) SQL Server Cursor [Why Peoples Hate Cursor?]....................................................................23
6) What is a trigger in SQL Server? Why use triggers?..............................................................25
7) What is a SQL Join? When would you use SQL Joins?.........................................................26
8) What is @@ERROR in SQL? When we should use @@ERROR?........................................29
9) How to Handle Error or Exception in SQL? When you use @@Error and TRY-CATCH?
.................................................................................................................................................................. 30
10) What is @@IDENTITY in SQL? When we should use and scope of @@IDENTITY?.....32
11) What is @@RowCount in SQL? What does this statement do @@RowCount?............33

2|Page
12) 3 Best Ways for 2nd 3rd 4th ...nth Highest Salary - [SQL Server]......................................35
16) What's new in SQL Server 2016?...............................................................................................36
18) MongoDB vs. SQL Server............................................................................................................39
19) SQL temp table vs table variable...............................................................................................39
23) What are different types of statements supported by SQL?...............................................40
24) How do we use DISTINCT statement? What is its use?.......................................................41
25) What are different Clauses used in SQL?................................................................................41
26) Why do we use SQL constraints? Which constraints we can use while creating
database in SQL?.................................................................................................................................43
28) What are transaction and its controls?....................................................................................43
29) What are properties of the transaction?..................................................................................43
30) How many Aggregate Functions are available there in SQL?............................................44
31) What are Scalar Functions in SQL?..........................................................................................44
37) What is SQL Injection?.................................................................................................................44
39) What is the difference between SQL and PL/SQL?...............................................................44
40) What is the difference between SQL and MySQL?................................................................44
42) What is the Cartesian product of table?...................................................................................44
45) What is the difference between clustered and non-clustered indexes?..........................45
46) What is the difference between DELETE and TRUNCATE?.................................................45
47) What is the difference between DROP and TRUNCATE?.....................................................45
50) What is Normalization? How many Normalization forms are there?................................45
56) What is Collation?.........................................................................................................................45
1) What is Routing Guard in Angular?.............................................................................................46
2) What are the differences between AngularJS (angular 1.x) and Angular (Angular 2.x
and beyond)?.........................................................................................................................................46
3) What is a component? Why would you use it?........................................................................47
4) What is the minimum definition of a component?...................................................................47
5) What's the difference between an Angular component and module?................................47
6) What is a module, and what does it contain?...........................................................................47
7) What is a service, and when will you use it?............................................................................48
8) What is the equivalent of ngShow and ngHide in Angular?..................................................48
9) What are pipes? Give me an example.........................................................................................48
10) You have an HTML response I want to display. How do I do that?....................................48
11) How can I select an element in a component template?......................................................48

3|Page
13) What is the difference between *ngIf vs [hidden]?................................................................48
14) What is the difference between "@Component" and "@Directive" in Angular?............49
16) How would you protect a component being activated through the router?....................49
17) What are some differences between Angular 2 and 4?........................................................49
18) How would you run unit test?.....................................................................................................49
19) What are the differences between Observables & Promises?...........................................50
20) What are differences between Constructors and ngOnInit?...............................................50
21) What are differences between Components and Directives?.............................................51
22) Why should `ngOnInit` be used, if we already have a `constructor`?..............................51
23) How to bundle an Angular app for production?....................................................................51
24) What is difference between "declarations", "providers" and "import" in NgModule....52
25) What is Reactive Programming and how to use one with Angular?.................................52
26) What's new in Angular 6 and why shall we upgrade to it?.................................................52
27) What are differences between MOCK VS STUB VS SPY?...................................................53
28) What is TestBed?...........................................................................................................................53
29) What is Protractor?......................................................................................................................53
32) What is AOT Compilation? - Pros and Cons of Ahead-of-Time!.........................................53
36) When would you use eager module loading? Or Name and explain some Angular
Module Loading examples.................................................................................................................54
37) What are the lifecycle hooks for components and directives?..........................................55
39) Could I use jQuery with Angular?..............................................................................................55
43) What is Zone in Angular?...........................................................................................................56
44) Why would you use lazy loading modules in Angular app?...............................................56
46) What does a just-in-time (JIT) compiler do (in general)?.....................................................56
48) What is ngUpgrage?......................................................................................................................56
49) Name some security best practices in Angular......................................................................57
51) Just-in-Time (JiT) vs Ahead-of-Time (AoT) compilation. Explain the difference............57
52) Do you know how you can run angularJS and angular side by side?..............................57
55) When to use query parameters versus matrix parameters?...............................................58
64) What is the difference between BehaviorSubject vs Observable?....................................58
65) What is the Angular equivalent to an AngularJS "$watch".................................................59
86) What Types of @NgModules?.....................................................................................................59
88) Why you use BrowserModule, CommonModule, FormsModule, RouterModule, and
HttpClientModule?................................................................................................................................60

4|Page
89) What are the differences in NgModules and JavaScript Modules?...................................60
92) What Are Angular Directives?.....................................................................................................60
93) What Are Angular Decorators?...................................................................................................61
94) What Is Compiler? Why we need compilation?......................................................................62
1. What Is Entity Framework?............................................................................................................62
2. What Is Csdl?....................................................................................................................................62
3. What Is Ssdl?....................................................................................................................................62
4. What Is Msl?......................................................................................................................................63
5. What Is Entity Data Model?............................................................................................................63
6. Which Are The Key Concepts Of Entity Data Model?..............................................................63
7. What Is Model First Approach?....................................................................................................64
8. What Is Code First Approach?......................................................................................................64
9. What Is Deferred Loading(lazy Loading)?..................................................................................64
10. What Is Eager Loading?...............................................................................................................64
11. What Is Conceptual Model?.........................................................................................................65
12. What Is Explicit Loading?............................................................................................................65
13. What Do You Mean By Navigation Property?..........................................................................65
14. What Is Entity Framework Advantage?....................................................................................65
15. Differences Between Poco, Model First And Data First Approach?..................................65
16. What Is Client Wins And Store Wins Mode In Entity Framework Concurrency?............66
17. Explain What Does .edmx File Contains?................................................................................66
18. How Can You Enhance The Performance Of Entity Framework?......................................66
19. Explain Why T4 Entity Is Important In Entity Framework?..................................................66
1. What Is Web Api?.............................................................................................................................67
2. What Is Rest?....................................................................................................................................67
3. Can We Do Unit Test Web Api?.....................................................................................................67
4. Can Web Api Return View In Mvc?...............................................................................................67
5. How To Restrict Access To Methods With Specific Http Verbs In Web Api?.....................67
6. What Is Web Api Routing?.............................................................................................................67
7. Differences Between Wcf And Web Api?....................................................................................68
8. What Are The Advantages Of Using Rest In Web Api?...........................................................68
9. With Wcf Also You Can Implement Rest, So Why Webapi?...................................................68
10. What Are The Advantages Using Webapi?..............................................................................68

5|Page
11. Differentiate Between Wcf And Web Api?................................................................................68
12. How Can We Register Exception Filters?................................................................................69

1. How the Encapsulation is different from Abstraction? I think both are


used to hide the unnecessary details? Then how they are different?
Yes, Both Encapsulation and Abstraction do the same thing but with few differences.
Encapsulation mainly encapsulates the object and so hides the details as well as it binds the
data.
So Encapsulation = Hiding + Binding the data
How it hides the data? Real-time Example?
Take the example of n-Tier application where we have an additional layer called Business
Objects. This layer
contains all the entities with their properties. Take an entity name: Employee. This Employee will
have the
class name "EmployeeBO.cs" and contains the public properties like EmpId, EmpName, Sal ets
EmployeeBO.cs

So this is the presentation of one property in the Business


object class. Now wherever we want this attribute,
We just need to create the object of this class and set/get the
value of EmpId as:
// set the EmpId
EmployeeBo objEmployeeBO = new EmployeeBO();
objEmployeeBO.EmpId = 101;

// get the EmpId


int empId = objEmployeeBO.EmpID;
Now the question is where its setting or getting the value?
EmpId is the public property in the EmployeeBO class and contain no value. Only _empId
contains the value
which is private and so it is not accessible.
So binding of the data happens to the EmpId through _empID and hiding happends through
_empId which is
private. The Data is accessed through the Public property while the actual data is in private
variable. So

6|Page
binding + hiding using Encapsulation.
Abstraction is to ignore the unnecessary details and get the required details. So it also hides
the unnecessary details. How?
Abstract class is the special type of class which can contain the abstract and
concrete members. If we define
The member (Method/Property) as abstract, it must be overrides to the child class. We are
not bothering here About the non-abstract or concrete members. Which is an unnecessary
detail? If we ad an additional concrete Member in the abstract class, we need not to
do anything in the child class. But if we add the abstract members, we must have to override it.
So abstract doesn't care about the concrete members which are unnecessary for it and so it
hides those details.

2. What do you mean by early binding and late binding in the object
bindings? Which is good? Please give me a scenario where you have
used the early binding and late binding concepts in your application?
In .Net, the early binding and last binding concepts comes under the polymorphism. As we know
that there are 2 types of polymorphism-
1. Compile Time polymorphism
2. Run time polymorphism
The Compile Time polymorphism also called as the Overloading where we have the same
method name with different behaviors. By implementing the multiple prototype of the same
method, we can achieve the behavior of the Overloading.
Also this behavior is valid only for a single class. It means we should have all the overloaded
methods in the same class.
e.g.

The Run time polymorphism also named as the Overriding. This concept works in between
classes or multiple classes or parent child classes where the child class has to get the behavior
of the base class by inheriting the base class.
In this concept we generally have an abstract or virtual method in the base class and we
override that method in the child class by using the override method.
e.g.

7|Page
So now we know the Compile Time polymorphism and Run Time polymorphism. The compile
time polymorphism uses the concept of early binding and Run time polymorphism uses it as the
late binding.
In early binding, the runtime (CLR) gets the behavior in the compilation of the program. It
means that the method behavior will get compiled before in the early binding.
In Late binding, like Overriding, the behavior of the class and methods gets by the CLR when
creating the object means at runtime. So, in the late binding the behavior of the class members
identified by the CLR at runtime.
Now come to the next part of the question-which is good?
One can’t say about the answer of this question, there are the scenarios where the early
binding is good. When you have lot of objects and in that case, the early binding behavior
performs well. While the late binding will be good when we have less objects. Let’s say you
want the dropdown list to be loaded when you click on it and not while the loading of the page.
So in some scenario, it will be good if we have while load and it will not be good when you click.
So it’s all depends on how you have implemented and the form structure.

3. In garbage collection, how the object generations come in the


picture? How many generations an object can have? Please tell me the
process of disposing the objects based on the generations? Can an
object move from one generation to another? If yes then why? What’s
the need to have different generations as we are going to dispose the
objects which are marked by the Garbage collector?
Ans.
Let’s start with what is Garbage collection first and then we will come to our main question of
the post. As we know that all the objects created using the new operator gets fits in to the Heap
memory. So whenever a new object gets created, it tries to fit in the heap memory. Now let’s say
the heap memory is full and there is no place to keep another newly created object.

8|Page
In that case the Garbage collector installed, which is the background process, runs through
CLR and take the unused objects memory. It mainly cleanup the heap memory and
the newobjects get placed in to it.
Now the question comes that for which objects it reclaims for the memory? How the object
generations come in the picture?
It depends on the objects generations. The CLR finds out the objects which are no longer
used by the application since longer time and then the Garbage collection reclaim their memory.
How many generations an object can have? Please tell me the process of disposing the
objects based on the generations?
Actually there are 3 generations exists for the objects which are written under the .Net
framework library. When a new object gets created, by default it moves to the generation 0.
Can an object move from one generation to another?
Now when the generation 0 objects gets occupied with the memory and garbage collector
gets called by the run-time. It checks the objects which are no longer used by the application
and mark them for deletion. After deleting or reclaim the memory, the older objects moved to
next generation i.e. Generation 1. Now the next time the CLR will check for the Generation 1
object too and if it finds that in generation 1 if the objects are not used since longer time, it will
mark them for release and move the remaining objects to generation 2.
In generation the objects which are under the main method, exists as they gets removed
either at the end of the program or when both the generation 0 and generation 1 objects are
using.
What’s the need to have different generations as we are going to dispose the objects which
are marked by the Garbage collector?
With the different generation, it improves the performance of the application as the Garbage
collector need not to check for each of the objects in the memory. It first checks for the
generation 0 objects and reclaim the memory. If still needs then goes to the generation 1 and
then 2.

4. What is object graph in garbage collector? Is this the graph physically


exists? Or how this graph gets created?

Ans. When the Garbage Collector gets called by the CLR to DE-allocate the memory in the
heap, the Garbage Collector start finding the references of all the reachable objects which are
currently in use. So it find the objects which are used by the processes and for rest of objects
which are un-reachable or the Garbage collector is not able to find the references for them, it
marks them for deletion.
Here the Garbage collector makes an Object graph which keeps track of all the objects which
are marked for deletion. After the deleting the references for those objects, the heap memory
gets compacted and a new root becomes available to use by the new created object.
Is this the graph physically exists? Or how this graph gets created?

9|Page
No, this object graph creates virtually by the Garbage Collector to keep all the objects and to
make them for deletion. This is the Garbage Collector responsibility to create this object graph
and gets the references of each reachable object which are used by the application

5. Can we suppress the Garbage collector? If yes, then why do we need


to suppress it as it is used to reclaim the unused memory and which
improve s the performance of our application?
Yes, We can suppress the Garbage Collector. There is the Static method in GC class called as
SupressFinalize.
GC.SuppressFinalize(objectName);
This Static method takes a parameter for the object. So we can pass it to suppress the
claiming memory for this object.
Now the question comes "why do we need to suppress it as it is used to reclaim the unused
memory",
So, whenever we are using dispose method for class object,which is capable of disposing the
object and in that case we don't need to use this method to again reclaim the memory.
e.g.
public class DemoClass : IDisposable

{
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
As we have seen above,the DemoClass is inherited by IDisposable interface and which have
the Dispose method to implement.
Hence after implementation of Dispose() method, we need not to reclaim the memory using
the Garbage collector and so we can use the SuppressFinalize() for the current class object.

6. We already have the Finalize method which reclaims the memory


using the Garbage collector. This is automatic process then why do we
have the Dispose () method? Is this method different from Finalize ()?
What is the interface from which the Dispose () method inherited?

Yes, We have the Finalize() method which is used to reclaim the memory for the unused
objects. The Finalize() method is sufficient to release the memory from heap for the un-
referenced object but it is only for the managed objects. So Finalize() method can reclaim the
managed objects memory from the heap which are not used since longer time.
Then what about the objects which are unmanaged? The objects which are out of .Net CLR?
The objects where the CLR can't be used to manage? Dispose() method is used for all those
objects which do not comes under CLR or under the Managed heap. Dispose() method can be
overrides and can be written to reclaim the object of those classes. Dispose() method is
implemented by using the IDisposable interface.
e.g.

10 | P a g e
public class TestClass : IDisposable
{

public void Dispose()


{
Dispose(true);
}

20. Why we used Inheritance. What is the benefit of this.


Inheritance is a way to inherit the base class members to the child class so that we can save lot
of memory.
let's say, if you are already having some properties defined in the base class and then if you are
inheriting this base class to the child class, the extra memory need not to be wasted to declare
the base class members again. While inheriting, automatically they will be inherited.
e.g.
class Mybase
{
int i, j;
float z;
}
class MyChild: Mybase
{
// no need to declare again the above variables
// as they will be automatically inherited.
}

As we need not to declare the variables again in the child class, so we have saved here 4 + 4 +
8 = 16 bytes of memory for the child class.
Main usage of inheritance is 'Re-usability'. No need to declare variables, methods again.. If u
want, then use them from base class. It reduce your code from complexity.

21. Why C# does not support Multiple Inheritance.


Multiple Inheritance is the situation in which when there are 2 base class and a single child
class is trying to inherit the members from both of them then there is the confusion that which
base class member should be inherited?
e.g.
class MyClass1
{
public void Show()
{
// something

11 | P a g e
}
}
class MyClass2
{
public void Show()
{
// something else
}
}
class MyChildClass: MyClass1, MyClass2
{
// not possible
}

Due to this, the architecture of .Net or the framework doesn't support such situation and will
throw the compile time error.
In C++, it is possible because there both the methods in the different base classes will have the
different memory location and object will be accessed through the memory location. But in Java
or .Net the object accessed through the class members objects.
It is quite difficult to implement multiple inheritance in C#. But we can do this through Interfaces.

22. Why we used virtual keyword.


If we want to override the members of the base class, we can make them as virtual. The virtual
members have the capability to override them in the child class. If they are not overridden, the
base class implementation will be executed.
It is not the mandatory to override the virtual class members.
e.g.
class MybaseClass
{
public virtual void Show()
{
Console.WriteLine("hey..I am in base class");
}
}

class MyChild: MyBaseClass


{
public override void Show()
{
Console.WriteLine("hey..I am in child class");
}
}

The preference will be given to child class always.

12 | P a g e
public static void Main(string[] args)
{
MyChild objChild = new MyChild();
objChild.Show(); // child class method will be called.
}

If a base class method needs to be overridden, it is defined using the keyword virtual (otherwise
the sealed keyword is used to prevent overriding).
24. What are events and actions in c#.
Events are the objects which are binded with the particular action. Whenever an action
happens, an event fires. Like button click event.The action is click and event is Button_Click
which is attached with the event handler to do the particular action and get the result.
29. Why we use Interface.
Interface is a way to use the global functionality throughout the application. If your application
require many unrelated object types to provide certain functionality then you go for interfaces.
It defines a contract between the application and the object.
Let's suppose we want to Show the data or Print the data in many pages of the application, we
can create a Interface which will contain the Abstract method and in the page where we want,
we can implement it as per our requirements.
e.g.

interface inf
{
void Print(); // abstract method
}
internal class MyClass: inf
{
public void Print()
{
// functionality to print to PDF document
}
}
internal class MyTest: inf
{
public void Print()
{
// functionality to print to tiff document
}
}
internal Class MyTest: inf
{
public void Print()
{

13 | P a g e
// functionality to print to .jpg format
}
}

We can see here we have separate classes and the implementation of the Print method is
different without making any changes in our interface.
So if we want to implement something global, we can use the Interface, for local or limited to
class, we can use the abstract class.
30. Why we use Method Overloading.
To reduce the memory and the good readability, we use the Overloading. This is the concept
where we can have the same method name for similar work with different behavior.
Let's say we want to get the Database connection based on the provider name to connect with
different databases, we can use the overloaded methods like:

public string GetConnectionString()


{
// return default connection string
}
public string GetConnectionString(string provider)
{
// return connection string based on provider name
}
31. Why we use Method Overriding.
Method overriding is the concept where we can use the same method in parent as well as in
child class to reduce the memory and use the similar behavior. If we don't want to change the
behavior, we need not to override it. So to make the changes in the behavior, we use the
overriding.
33. In which case we can use Abstract class in our project.
Abstract class is always used when we have the limited scope or the objects are of similar
types.
e.g. Lets suppose we want to get the area of few objects. This is not the global where we need
to do.
So we can create the abstract method to calculate the area and then according to shape, we
can override them. So here the scope is limited and will not be used throughout the application.
Hence we can use the abstract class.
34. What is the difference between Array List and Ilist.
IList is an interface for the implementing the List collection.
As the List is the generic so we can use it to restrict the type of the list e g.
List objList = new List();
It means, the List object is restricted to the int. We can't insert here any type of data in to list.
Only the int is permitted.
ArrayList is the collection where we can insert any type of data as:
ArrayList objArrayList = new ArrayList();

14 | P a g e
objArrayList.Add("Hello");
objArrayList.Add(1);
objArrayList.Add("Sure");
The ArrayList will not check the type in the compilation of the program.
35. What is difference between internal class and sealed class.
The internal class object can be used with-in the assembly and not outside of the assembly.
These classes can be inherited.
Sealed classes are those classes which doesn't need anything from outside. These are full
classes.
These classes can't be extended.
37. What is the difference between Remoting and web service.
Remoting is the concept of calling the remote interfaces like communication with the
heterogeneous applications but both should be developed using the same .Net language.
For the client and server communication, we use the Remoting.
Remoting is the platform dependent so both the client and server must be built in .Net
Technology and both the systems should use the CLR.
Web-service is small logic which runs on the internet. It is used for the heterogeneous
applications and consume the service in any application. It is platform independent so no need
to have the CLR or .net framework to be installed on the machines. C++ web service can be
consumes in .Net application.
40. What is type safety in .NET?
Type safety in .NET has been introduced to prevent the objects of one type from peeking into
the memory assigned for the other object. Type safety helps the compiler and CLR in .NET to
execute the code in the memory space defined for the objects and instances. It further helps to
build the robust and error free applications which are definitely error free at run time.
An excellent example of type safety is the following example –
private void ChangeValue(out object par)
{
par = new String('x', 10);
}
SomeOtherType obj = new SomeOtherType();
ChangeValue(out obj); //compile time error

If .NET would have allowed this code to execute, type safety could have easily been
compromised here resulting in some unpredictable results and hence in turn reducing the
credibility of the code.

50. What are static classes.


Static classes are the classes which cannot be instantiated. These classes cannot be derived
from and the method parameters cannot be of type static class. These classes are loaded once
per app domain and they are loaded as soon as any member variable or function is called for
that class. One class is shared across the whole application.

51. When are static classes initialized.

15 | P a g e
The static classes are loaded in the memory as soon as any of the data member or the function
member is called for the first time.

52. What is difference between static class and singleton class.


Static class
Cannot be initialized
Cannot be the base class
Cannot be the parameter to a function
All the member variables and functions should be static
Can have only static constructor.
Singleton Class (You can read about it here)
Can have only one instance per app domain
Can be passed as parameter to a function.
Singleton class usually have a single private constructor

53. Is it possible to have a static constructor in class. If yes why do we


need to have a static constructor.
Static constructors are used to initialize the static member variables of the class. Hence a static
constructor executed once per type instead of once per instance. A type can define only one
static constructor and it must be parameterless. The runtime automatically invokes a static
constructor just prior to type being used. Two things trigger this-

 Instantiating the type


 Accessing a static member in the type.
class TestClass
{
static Test(){ Console.WriteLine("Type Initialized"); } }

54. What are delegates.


Delegates are reference types which are used to contain the function pointers. Delegates are
type safe and they adhere to compile type safety. A delegate can declared as following –

public delegate void MyDelegate(int number);

This is a delegate which would contain a reference to a function which should return void and
take one parameter of type int. You can learn more about delegates in my article.
55. What is a multicast delegate.
Each delegate type is derived from Multicast delegate, which would help to have a invocation
list for each and every delegate. Having an invocation list means that we can attach multiple
methods attached to a delegate which would be called one after the other in the order which
they are added to the delegate. Since multiple methods can be called using delegates that is
why it is generally advise to have void as return type of multicast delegate.
56. How can we achieve asynchronous programming using delegates.
We can call a method asynchronously using the delegate by using the BeginInvoke() function of
the delegate.

16 | P a g e
57. Are delegates type safe.
Yes delegates are type safe and at compile time itself we can get to know the parameter type
and return type of a delegate. More about type safety in my article

58. What is the difference between Convert.ToSting() and


Object.ToSting() instance method of a class.
Convert.ToString() can handle the NULL values but ToString() cannot handle null, it will throw
object reference null exception and we can override Object.ToString() to provide custom
implementation for the class

63. What is C#?


C# is an object oriented, type safe and managed language that is compiled by .Net framework
to generate Microsoft Intermediate Language.

67. What is an object?

An object is an instance of a class through which we access the methods of that class. “New”
keyword is used to create an object. A class that creates an object in memory will contain the
information about the methods, variables and behavior of that class.

68. Define Constructors?


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

71. What is the use of using statement in C#?


The using block is used to obtain a resource and use it and then automatically dispose of when
the execution of block completed.

72. What is serialization?


When we want to transport an object through network then we have to convert the object into a
stream of bytes. The process of converting an object into a stream of bytes is called
Serialization. For an object to be serializable, it should implement ISerialize Interface. De-
serialization is the reverse process of creating an object from a stream of bytes.

74. What is difference between constants and read-only?


Constant variables are declared and initialized at compile time. The value can’t be changed
afterwards. Read only is used only when we want to assign the value at run time.

78. What are sealed classes in C#?

17 | P a g e
We create sealed classes when we want to restrict the class to be inherited. Sealed modifier
used to prevent derivation from a class. If we forcefully specify a sealed class as base class
then a compile-time error occurs.

83. What are the differences between System.String and


System.Text.StringBuilder classes?
System.String is immutable. When we modify the value of a string variable then a new memory
is allocated to the new value and the previous memory allocation released.
System.StringBuilder was designed to have concept of a mutable string where a variety of
operations can be performed without allocation separate memory location for the modified
string.

84. What’s the difference between the System.Array.CopyTo() and


System.Array.Clone() ?
Using Clone() method, we creates a new array object containing all the elements in the original
array and using CopyTo() method, all the elements of existing array copies into another existing
array. Both the methods perform a shallow copy.

88. What is the difference between Finalize() and Dispose() methods?


Dispose() is called when we want for an object to release any unmanaged resources with them.
On the other hand Finalize() is used for the same purpose but it doesn’t assure the garbage
collection of an object.

90. What are generics in C#.NET?


Generics are used to make reusable code classes to decrease the code redundancy, increase
type safety and performance. Using generics, we can create collection classes. To create
generic collection, System.Collections.Generic namespace should be used instead of classes
such as ArrayList in the System.Collections namespace. Generics promotes the usage of
parameterized types.

91. What is an object pool in .NET?


An object pool is a container having objects ready to be used. It tracks the object that is
currently in use, total number of objects in the pool. This reduces the overhead of creating and
re-creating objects.

102. What is the difference between a Struct and a Class?


Structs are value-type variables and classes are reference types. Structs stored on the stack,
causes additional overhead but faster retrieval. Structs cannot be inherited.

105. What is difference between is and as operators in c#?


“is” operator is used to check the compatibility of an object with a given type and it returns the
result as Boolean.

“as” operator is used for casting of object to a type or a class.

18 | P a g e
107. What are indexers in C# .NET?
Indexers are known as smart arrays in C#. It allows the instances of a class to be indexed in the
same way as array.

Eg:
1 public int this[int index] // Indexer declaration

1) What is store procedure? How do they work? When do you use?


A stored procedure is a collection of SQL statements that has been created and stored in the
database.

It is a set of recompiled SQL statements that are used to perform a special task.

Stored procedures create once a time and calls it n number of times and also reduces the
network traffic and increase the performance.

When do you use store procedure?


I used store procedures in 1 of 3 scenarios,
 Security,
 Speed and
 Transactions

Types of SQL Procedures,


1. System Stored Procedures
2. User Defined Stored Procedures
3. Extended Stored Procedures

The SQL Stored Procedure Summary:-


1. Stored Procedure may or not return values.
2. Stored Procedure can have both input and output parameters.
3. Stored Procedures can call functions.
4. We can use exception handling in the Stored Procedure using try catch blocks.
5. We can use transactions within Stored Procedures but not in function.
6. We can use both table variables as well as temporary table in it.
7. We can’t use Stored Procedures in the SELECT, WHERE and HAVING statements.

2) SQL Server Functions,Types and Examples


What is a function in SQL Server?
A SQL function is a set of statements that you can pass input values, perform an action and
return the result and the result can be single value or a table value.
When do you use SQL function?
When I am writing an expression and I want to return some value in the SELECT statement
from this expression that time I can use a function.

19 | P a g e
Types of SQL functions,
1) System defined functions
· Scalar Functions: - abs, round, upper, lower, trim and convert etc.
· Aggregate Functions: - min, max, avg and count etc.
2) User defined functions
The user defined functions are created in the user defined database. This user defined function
can be “inline table valued function”, “scalar value function” or “multi statement table valued
function”.
The SQL function Summary:-
1. SQL function must be be return a value or a table value.
2. SQL function accepts only input parameters.
3. SQL functions can’t use in insert, update and delete in the database tables.
4. SQL functions can be nested up to 32 levels.
5. The user defined SQL function can have up to 1023 input parameters.
6. The user defined SQL function can't return XML data type and it is not support to
exception handling.
7. It is only call in the stored procedures and it is not support to the set options like
ROWCOUNT etc.

3) What is SQL view? Why use View instead of a Table? Advantages and
Drawbacks
What is SQL view?
The View is a virtual table, which not create physically, it create logically only. We insert, update
& delete the records from a view.
In view there are no any physical relations in the database and the view is a virtual table based
on the result set of an SQL statement.
Why use View instead of a Table?
A table contains data but the View dose not stored set of data values in a database and the view
is only a SELECT statement.
A view can combine columns/rows from multiple tables.
Views are work like a security layers and we can handle security issues.
Views can be used as security mechanisms and its display only those data that you granting the
permissions in this view.
Advantages of View:-

20 | P a g e
We can hide so of table columns.
Views can model complex joins easily.
Views are work like a security layers and we can handle security issues.
Drawbacks of View: -
When table is dropped or modified, view becomes inactive; it depends on the table objects.
If we querying from views, it will takes more time than directly querying from the tables.
We can lose information about relations (primary, foreign keys).
How to create View “Virtual Table”?
Syntax:-
-- CREATE VIEWS
CREATE VIEW View_Name
AS
SELECT Column_Name
FROM Table_Name
WHERE your_Conditions

Example for Create View:-

-- CREATE ACTIVE CUSTOMERS VIEWS


CREATE VIEW vw_Active_Customers
AS
SELECT Id, Name, CreatedOn, UpdatedBy
FROM [dbo].[Customer]
WHERE IsCurrent = 1

-- SELECT ACTIVE CUSTOMERS VIEWS


SELECT * FROM [dbo].[vw_Active_Customers]

-- DROP VIEW
DROP VIEW [dbo].[vw_Active_Customers]

4) What is Index? How do database indexes work? How do indexes help,


Types?
What is an index in SQL?
An index is created in a table to increase the performance of queries and the data pages are
stored contiguously when the index is created and when the index is new-built.
Index allows us to retrieve very fast data from the database and allow us to searching millions of
records quickly.

21 | P a g e
How do database indexes work?
There are some strategies that make indexes work,
1. Optimize your code.
2. Restructure your data.
3. Compress your data.
4. Materialize them.
5. Redundancy
How do indexes help?
For Example, suppose is a student and studying a book and this book contains 10,000 pages.
In the first day I read some topic “abc” and next day I want to read some another topic “pqr”. I
will never manually go through page by page. It is very difficult to go there. In this situation, I
am using book index to find specific topic and go directly to this page because IDEX allow us to
search millions of record quickly!
What types of indexes?
1. Clustered
2. Non-clustered
3. Unique
4. Index with included columns
How does an index improve performance?
An index is a way to physically re-organise the records and used to run faster queries.
The index can be used as a pointer to the large table. It helps to find row quickly and then return
back to the user.
What are some best practices for creating indexes?
Some of the rules are to creating index as,
1. Index ALL primary keys columns (It is default).
2. Index ALL foreign keys columns
3. You create more indexes only when the queries are too slow otherwise ignoring it.

The examples are,


-- CREATE INDEX
CREATE INDEX INDEX_NAME ON TABLE_NAME;

22 | P a g e
-- CREATE SINGLE COLUMN INDEXE
CREATE INDEX INDEX_NAME ON TABLE_NAME (COLUMN_NAME);
-- CREATE UNIQUE INDEXE
CREATE UNIQUE INDEX INDEX_NAME ON TABLE_NAME (COLUMN_NAME);
-- CREATE COMPOSITE INDEXE
CREATE INDEX INDEX_NAME ON TABLE_NAME (COLUMN_NAME_1, COLUMN_NAME_2);
--DROP INDEX
DROP INDEX INDEX_NAME;

5) SQL Server Cursor [Why Peoples Hate Cursor?]


“What is a Cursor in SQL Server”? “What is the exact use of Cursor”? “Why
do people hate SQL Cursor”?
A Cursor is a database object. Cursor is used, when you need to enumerate table records in
row by row basic that means singleton fashion.
Its work likes a RecordSet in the ASP.Net.
We can say that a Cursor is a set of rows with a pointer that identify a current row.
Why is it considered to use cursors in SQL Server?
Why do people hate SQL cursors so much?
Actually, the main reason of avoid cursor is “cursors take up memory and create locks” and
also create performance issues.
What are the Alternatives of cursor?
As per my thought, I am trying to use a “while loop” at the place of CURSOR to resolve this
locking issues.
The “while loops” are easy to use as a cursor but it’s sometime created more difficulty to
understand.
The main advantage of “while loop” is that no objects must be created in memory to facilitate the
looping.

How to Create Cursor in Sql Server?


--How to Create Cursor in Sql Server?
--STEP1: DECLARE A CURSOR
DECLARE @EmpName VARCHAR(50)
DECLARE @EmpDepartment VARCHAR(50)

--STEP2: DEFINE A CURSOR


DECLARE Cursor_Emply CURSOR FOR

23 | P a g e
SELECT EmpName, EmpDepartment FROM Emply

--STEP3: OPEN A CURSOR


OPEN Cursor_Emply

--STEP4: FETCH A CURSOR


FETCH Cursor_Emply INTO @EmpName, @EmpDepartment
WHILE(@@fetch_status=0)
BEGIN
PRINT '* EmpName= '+@EmpName
PRINT ' EmpDepartment= '+@EmpDepartment

--FETCH CURSOR FOR NEXT ROWS


FETCH Cursor_Emply INTO @EmpName, @EmpDepartment
END

--STEP5: CLOSE A CURSOR


CLOSE Cursor_Emply

--STEP6: DEALLOCATE A CURSOR


DEALLOCATE Cursor_Emply

How to Call a Cursor in Store procedure?

--How to Call a Cursor in Store procedure?


--CREATE PROCEDURE
CREATE PROCEDURE SPCursor_Emply
AS BEGIN
DECLARE @EmpName VARCHAR(50)
DECLARE @EmpDepartment VARCHAR(50)

DECLARE Cursor_Emply CURSOR FOR


SELECT EmpName, EmpDepartment FROM Emply

-- OPEN CURSOR
OPEN Cursor_Emply

-- FETCH CURSOR
FETCH Cursor_Emply INTO @EmpName,@EmpDepartment
WHILE(@@fetch_status=0)
BEGIN
PRINT '* EmpName= '+@EmpName
PRINT ' EmpDepartment= '+@EmpDepartment

--FETCH CURSOR FOR NEXT ROWS


FETCH Cursor_Emply INTO @EmpName, @EmpDepartment
END

-- CLOSE CURSOR
CLOSE Cursor_Emply

24 | P a g e
-- DEALLOCATE CURSOR
DEALLOCATE Cursor_Emply

END

How to use a “while loop” with select statement in SQL Server?


--WHILE LOOP WITH SELECT STATEMENT
DECLARE @Age INT
SET @Age = 30
WHILE (@Age >=18)
BEGIN
PRINT @Age
SET @Age = @Age + 1
END
GO

-- WHILE LOOP WITH CONTINUE AND BREAK KEYWORDS


DECLARE @Age INT
SET @Age = 30
WHILE (@Age >=18)
BEGIN
PRINT @Age
SET @Age = @Age + 1
CONTINUE;

IF @Age = 45 -- WILL NEVER EXECUTED!


BREAK;
END
GO

6) What is a trigger in SQL Server? Why use triggers?


What is a trigger in SQL? Why use triggers?
A trigger is a special kind of operations that execute automatically when an event occurs in the
database (tables and views) when you trying to INSERT, UPDATE OR DELETE operations in
the tables and views.
All the triggers are directly attached with the tables and views. Each of the tables has their own
trigger.
Noted Points:-
1. We can’t create triggers against the system tables and views.
2. The AFTER triggers can’t be defined on the views.
3. You try to avoid using nested triggers.

25 | P a g e
4. You try to avoid using recursive triggers.

What types of trigger in SQL Server?


There are two types of Triggers available in the SQL that is
DML Triggers: - i) After Trigger ii) Instead of Trigger
DDL Triggers
There are three query actions that are used in SQL INSERT, UPDATE OR DELETE.
Syntax:-
--CREATE DATABASE TRIGGER TEMPLATE
CREATE TRIGGER <trigger_name, sysname, table_alter_drop_safety> ON DATABASE
FOR <data_definition_statements, , DROP_TABLE, ALTER_TABLE>
AS
IF IS_MEMBER ('db_owner') = 0
BEGIN
PRINT 'You must ask your DBA to drop or alter tables!'
ROLLBACK TRANSACTION
END
GO

How to create triggers?


--How to Create trigger?
--CREATE TRIGGER
CREATE TRIGGER myTrigger3 ON employee
FOR UPDATE, INSERT, DELETE
AS
-- BEFORE INSERT
SELECT 'Before INSERT'
INSERT Employee (ID, Name) VALUES (31, 'Rick')
GO
--BEFORE UPDATE
SELECT 'Before UPDATE'
UPDATE Employee
SET Name = 'Test'
WHERE ID = 1
GO

-- BEFORE DELETE
SELECT 'Before DELETE'
DELETE FROM Employee
WHERE ID = 1

7) What is a SQL Join? When would you use SQL Joins?


What is a SQL Join? When would you use Joins?

26 | P a g e
Join is used to fetch data rows from more than one tables simultaneously based on your join
conditions.
Types of joins in SQL:-
1. INNER JOIN
2. OUTER JOIN
a. Right Outer Join
b. Left Outer Join
c. Full Outer Join
3. SELF JOIN
4. CROSS JOIN
5. MULTIPLE JOIN
All the Joins are work between the table’s key relations.

What is inner join in SQL? when would you use it?


Inner Join returns the matched rows from both the tables. If both the keys are matched then
return rows otherwise not!

What is Left Outer Join in SQL? when would you use it?

In the LEFT OUTER JOIN, returns all the matched rows from the left table and matched rows
from right table. If the right table is not matched then will return NULL values.

27 | P a g e
What is Right Outer Join in SQL? when would you use it?

In the RIGHT OUTER JOIN, returns all the matched rows from the right table and matched rows
from left table. If the left table rows are not matched then return NULL values.

What is Full Outer Join in SQL? when would you use it?

FULL OUTER JOIN work between with both the LEFT OUTER and RIGHT OUTER JOINS. If
the condition is matched then returns matched rows otherwise returns NULL values.

28 | P a g e
What is SELF JOIN and when would you use it?
A SELF JOIN is join which is used to join a table to itself.

There is no SELF JOIN keyword and it is used to compare values in a column with other values
in the same column in the same table.

For example,

SELECT * FROM TableA t1, TableA t2


WHERE t1.Id = t2.Id

In the above query, WHERE clause could be any given expression as per you!

8) What is @@ERROR in SQL? When we should use @@ERROR?


What is @@ERROR in SQL?
@@ERROR returns only current error information (error number and error) after T-SQL
statements executed.
@@ERROR returns 0, if the previous SQL statement has no errors otherwise return 1.
@@ERROR is used in basic error handling in SQL Server and @@ERROR is a global variable
of SQL and this @@ERROR variable automatically handle by SQL. If error is occurred set error
number otherwise reset 0.
It is work only within the current scope and also contains the result for the last operation only.
Syntax: - @@ERROR
Return Type: - INT
When we should use @@ERROR?
1. While executing any stored procedures
2. In the SQL statements like Select, Insert, Delete and Update etc.
3. In the Open, Fetch Cursor.
When we should use Try Catch Block?
The Try Catch Block is generally used where want to catch errors for multiple SQL statements.
The example as,
-- DECLARE RETURN TABLE
DECLARE @Return_Table TABLE (Code varchar(10)
,Message varchar(100), ID varchar(100))

29 | P a g e
--UPDATE CUSTOMER QUERY
UPDATE Customer
SET Name = N'Anil Singh'
WHERE Id = 0786

--USE OF @@ERROR
IF (@@ERROR <> 0)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'An error occurred in updating the customer.', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
ELSE IF (@@ERROR = 1087)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'Must declare the table variable @Return_Table.', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
ELSE IF (@@ERROR = 547)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'A check constraint violation occurred.', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
ELSE
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'OK', 'SUCCESS', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
GO

9) How to Handle Error or Exception in SQL? When you use @@Error


and TRY-CATCH?
Today's, I am going to share the code sample for exception handling in SQL Server; The SQL
Server exception handling is very similar to the Microsoft C# and C++ etc.
Error Handling Mechanism:-
The two types of error handling in SQL Server that is
1. @@ERROR
2. TRY CATCH Block

When we should use @@ERROR?


1. While executing any stored procedures
2. In the SQL statements like Select, Insert, Delete and Update etc.

30 | P a g e
3. In the Open, Fetch Cursor.
When we should use Try Catch Block?
The Try Catch Block is generally used where want to catch errors for multiple SQL statements.
In the SQL Server, The TRY CATCH are catches all errors and store in the @ERRORS variable
and raise the errors using the RAISERROR().
Following functions are used in CATCH block,
ERROR_NUMBER(): Will return error number.
ERROR_SEVERITY():Will return severity level.
ERROR_STATE():Will return state number.
ERROR_LINE():Will return error line number.
ERROR_PROCEDURE():Will return stored procedure name that occurred the error.
ERROR_MESSAGE():Will return full message text of the error.
Syntax:-
BEGIN TRY
---YOUR CODE LOGIC
END TRY
BEGIN CATCH
---YOUR ERRORS HANDLER
END CATCH

The example as,

-- ============================================================
-- ABOUT : TRY CATCH IN SQL SERVER STORED PROCEDURE
-- CREATE DATE: 22/04/2015
-- DESCRIPTION: RETURNS [LISTEVENT]
-- PARAMETERS: FROMDATE, TODATE
-- =============================================================
CREATE PROCEDURE [SPX].[LISTEVENT]
(
@FROMDATE DATETIME,
@TODATE DATETIME
)
AS BEGIN
BEGIN TRY
SELECT EVENTDESC,
EVENTNAME,
STARTDATE,
ENDDATE
FROM SPX.SPORTPIXPROMOEVENTS
WHERE STARTDATE=@FROMDATE AND ENDDATE=@TODATE

31 | P a g e
END TRY

BEGIN CATCH
DECLARE @ERRORS VARCHAR(8000)
SET @ERRORS= CONVERT(VARCHAR,ERROR_NUMBER()) + '*****' +
CONVERT(VARCHAR(4000),ERROR_MESSAGE()) + '*****' +
ISNULL(CONVERT(VARCHAR,ERROR_PROCEDURE()),'GETPROMOTIONLIST') +
'*****' +
CONVERT(VARCHAR,ERROR_LINE()) + '*****' +
CONVERT(VARCHAR,ERROR_SEVERITY()) + '*****' +
CONVERT(VARCHAR,ERROR_STATE())

RAISERROR (@ERRORS, -- MESSAGE TEXT.


16, -- SEVERITY.
1 -- STATE.
);
END CATCH
END

10) What is @@IDENTITY in SQL? When we should use and scope of


@@IDENTITY?
What is @@IDENTITY in SQL?
The @@IDENTITY is a system function which returns the last inserted identity value.
All the @@IDENTITY, SCOPE_IDENTITY and IDENT_CURRENT are similar functions
because all are return the last inserted value into the table’s IDENTITY columns.

The @@IDENTITY and SCOPE_IDENTITY return the current session last identity value but the
SCOPE_IDENTITY returns the current scope value.
What is the scope of @@IDENTITY?
In the @@IDENTITY, there are no any limitations for a specific scope.
Syntax: - @@IDENTITY
Return Type: - numeric (38, 0)
For example as,

-- USE OF @@IDENTITY
INSERT INTO ContactType(Code, Description, IsCurrent, CreatedBy, CreatedOn)
VALUES ('IT-PROGRAMING', 'This is a Prrogrammer!', 1, 'Anil Singh', GETDATE());
GO
SELECT @@IDENTITY AS 'COL_IDENTITY';
GO

32 | P a g e
The Use of SCOPE_IDENTITY :-
-- DECLARE RETURN TABLE
DECLARE @Return_Table TABLE (Code varchar(10)
,Message varchar(100), ID varchar(100))

--INSERT CONTACT TYPE


INSERT INTO ContactType(Code, Description, IsCurrent, CreatedBy, CreatedOn)
VALUES ('IT-PROGRAMING', 'This is a Prrogrammer!', 1, 'Anil Singh', GETDATE());

--USE SCOPE_IDENTITY
IF (@@ERROR <> 0)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'An error occurred in updating the customer.', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
ELSE
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'OK', 'SUCCESS', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
GO

11) What is @@RowCount in SQL? What does this statement do


@@RowCount?
The @@ROWCOUNT is a special variable of SQL. It will return the number of rows changed by
the last statement.
The @@RowCount is equal to (=) the number of rows changed by the last statement.

Syntax: - @@ROWCOUNT
Return Types: - INT

What is the scope of @@RowCount?


The @@RowCount is both the scope and connection safe and it is read only!

For example as,


-- DECLARE RETURN TABLE
DECLARE @Return_Table TABLE (Code varchar(10)
,Message varchar(100), ID varchar(100))

--UPDATE CUSTOMER QUERY


UPDATE Customer
SET Name = N'Anil Singh'
WHERE Id = 0786

33 | P a g e
--USE OF @@ROWCOUNT
IF (@@ROWCOUNT > 0)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'OK', 'SUCCESS', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
ELSE
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'Warning - No rows updated.', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
GO

Keep in Mind an Interesting point:-


@@ROWCOUNT is returns only integer value. Suppose that, you are working on bulk insert
operations and you are updating millions of records in the database table that
time @@ROWCOUNT is fail to returns the count values because it is an integer return types
and your effected millions of rows in the table.
In that case, we are using ROWCOUNT_BIG() method to achieve this because it is bigint
returns types.
Syntax: - ROWCOUNT_BIG()
Return Types: - BIGINT

For example as,


-- DECLARE RETURN TABLE
DECLARE @Return_Table TABLE (Code varchar(10)
,Message varchar(100), ID varchar(100))

--INSERT CUSTOMER ROWS


INSERT INTO ContactType(Code, Description, IsCurrent, CreatedBy, CreatedOn)
VALUES ('IT-PROGRAMING', 'This is a Prrogrammer!', 1, 'Anil Singh', GETDATE());

--USE OF ROWCOUNT_BIG() METHOD


IF (ROWCOUNT_BIG() > 0)
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'OK', 'SUCCESS', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END
ELSE
BEGIN
INSERT INTO @Return_Table (Code, Message, ID)
SELECT 'ERROR', 'Warning - No rows updated.', SCOPE_IDENTITY()
SELECT Code, Message, ID FROM @Return_Table
END

34 | P a g e
GO

12) 3 Best Ways for 2nd 3rd 4th ...nth Highest Salary - [SQL Server]
Method 1 :-
SQL Server 2nd, 3rd, 4th... Highest salary using SUB QUERY!
We can find the 2nd, 3rd, 4th ... nth highest salary using SQL Server the below query, In the below
query use top 1 for the 2nd highest salary, top 2 for the 3rd highest salary, top 3 for the 4th highest
salary,.... nth for the (n+1) highest salary.
Method 2:-
You can use LIMIT to get 2nd, 3rd, 4th ... nth highest salary!
The examples using SUB QUERY,
--QUERY FOR THE 2ND HIGHEST SALARY
SELECT MAX(salary) AS [2ndHighestSalary]
FROM Employee WHERE salary not in (SELECT TOP 1 salary FROM Employee
GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE 3RD HIGHEST SALARY


SELECT MAX(salary) AS [3rdHighestSalary]
FROM Employee WHERE salary not in (SELECT TOP 2 salary FROM Employee
GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE 4TH HIGHEST SALARY


SELECT MAX(salary) AS [4thHighestSalary]
FROM Employee WHERE salary not in (SELECT TOP 3 salary FROM Employee
GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE 5TH HIGHEST SALARY


SELECT MAX(salary) AS [5thHighestSalary]
FROM Employee WHERE salary not in (SELECT TOP 4 salary FROM Employee
GROUP BY salary ORDER BY salary DESC)

--QUERY FOR THE NTH HIGHEST SALARY


SELECT MAX(salary) AS [nthHighestSalary]
FROM Employee WHERE salary not in (SELECT TOP (n-1) salary FROM Employee
GROUP BY salary ORDER BY salary DESC)

In MySQL simple and sweeter 2nd, 3rd, 4th... Highest salary.


You can use LIMIT to get highest salary!
Examples using MySQL LIMIT,
--QUERY FOR THE 2ND HIGHEST SALARY USINGH LIMIT
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 1, 1;

--QUERY FOR THE 3rd HIGHEST SALARY USINGH LIMIT

35 | P a g e
SELECT salary FROM Employee ORDER BY salary DESC LIMIT 2, 1;

--QUERY FOR THE 4th HIGHEST SALARY USINGH LIMIT


SELECT salary FROM Employee ORDER BY salary DESC LIMIT 3, 1;
16) What's new in SQL Server 2016?
Top 6 Features Coming to SQL Server 2012
1. In SQL Server 2012, uses 48 bit precision for spatial.
2. In SQL server 2012, has unlimited concurrent connections are available.
3. In SQL server 2012, by default supports 15,000 partitions in DB.
4. In SQL server 2012, available new string function CONCAT to strings.
5. In SQL server 2012, available new string function FORMAT to strings.

6. In SQL server 2012, available new conversion functions are PARSE, TRY_CONVERT,
and TRY_PARSE.
What is difference between SQL 2012 and 2016?
Top 7 Features Coming to SQL Server 2016, lets see in the detail with examples.

1. Query Store
2. Polybase
3. Stretch Database
4. JSON Support
5. Row Level Security
6. Always Encrypted
7. In-Memory Enhancements
Query Store

36 | P a g e
Microsoft is maintain query store upgrading most of all versions but What happen in this
version?
Actually In this version Microsoft trying to maintains a history of query execution plans with
query performance and quickly queries etc.

PolyBase

Microsoft is introduced Polybase, This is data processing technique that is called SQL Server
connector.

This SQL connector provide the connectivity to Azure Blob Storage and Hadoop using database
tables query and Its dealing to a lot of large text files.
Stretch Database

37 | P a g e
In this section, Microsoft is trying to reduce your storage cast by a hybrid feature that is called
Stretch Database.
JSON Support
JSON Support Is very awesome features, Using this features you can direct querying to
Hadoop, SQL Server 2016 and also support to Lingua Franca.
Row Level Security
The SQL Server 2016 provide row-level security. It's very useful for multi tenant environments
and Its provide the limit to access the data based on role etc.
Always Encrypted

The SQL Server 2016 has feature to supported both column level encryption and encryption in
transit as well.

38 | P a g e
The Always Encrypted mechanism provided a easy way to encryption to data and makes much
better security.
In-Memory Enhancements

This feature already introduce in SQL Server 2014 but it has some limitation over data and
issues like no-locking-issues and high-volume-session state issues.

Now in SQL Server 2016, Fixed the issues and trying to improved memory mgmt and Its also
supporting foreign keys, check and unique constraints and parallelism also.

Insert multiple level JSON data into SQL Server 2016 -


Now Native JSON support in SQL Server 2016 and it provides you some functions to read and
parse your JSON object to table format.

1. The OPENJSON () table value function transforms JSON object to one or many rows. It will
not execute any command. It just returns a table row if JSON text is properly formatted.
OPENJSON function will also work with JSON arrays and this function can also open
nested/hierarchical JSON objects. OPENJSON will just return set of rows instead of single row.
2. The JSON_Value () is a scalar function and used to returns a value from JSON on the
specified path.
There are some specific examples for OPENJSON read nested JSON –

18) MongoDB vs. SQL Server


The MongoDB store the data in documents with JSON format but SQL store the data in Table
format.

The MongoDB provides high performance, high availability, easy scalability etc. rather than
SQL Server.

39 | P a g e
MongoDB mentioned to document-based NoSQL databases but SQL Server mentioned to
relational database.
MongoDB is a NoSQL database so there's nothing like a stored procedure. You can create a set
of common functionality in a class library.
The "fire-and-forget" is a default option to check query operations but we can use to
"getLastError" method to check query operations succeeded or not.

In the MongoDB, we can change the structure simply by adding, removing column from the
existing documents.

19) SQL temp table vs table variable


There are some differences between “Temporary Tables” (#tempTable) and “Table Variables”
(@tempTable).
Point 1:
A Temp table (#tmp) can do all the DDL operations and it allows creating the indexes, altering
and dropping.
A Table variable (@tmp) is not allowed doing the DDL operations but can create the clustered
index only.
Point 2:
A Temp table (#tmp) is easy to create and back up your data.
A Variable table (@tmp) is easy to create but involves the extra effort for create the normal
tables and then back up your data.
Point 3:
A Temp table (#tmp) result can be used by multiple users.
A Variable table (@tmp) result can be used by the current user only.
Point 4:
A Temp table (#tmp) will be stored in the tempdb and create network traffic. If we have large
amount of data in the temp table and it will create performance issue.
A Table variable (@tmp) will be store in the physical memory for some of the data, and then
later when the size increases it will be moved to the tempdb.
Point 5:
A Temp table (#tmp) can be used for the current session or global, so that multiple user session
can utilize the results in the table.
A Table variable (@tmp) can be used inside program, function or procedures.

Point 6:

40 | P a g e
In the Temp table (#tmp), function not allows us to use the Temp table.
In the Table variable (@tmp), function allows us to use the table variable.

23) What are different types of statements supported by SQL?

There are 3 types of SQL statements


1) DDL (Data Definition Language): It is used to define the database structure such as tables.
It includes three statements such as Create, Alter, and Drop.
Some of the DDL Commands are listed below
 CREATE: It is used for creating the table.
CREATE TABLE&amp;amp;amp;nbsp;table_name

column_name1 data_type(size),

column_name2 data_type(size),

column_name3 data_type(size),

 ALTER: The ALTER table is used for modifying the existing table object in the database.
ALTER TABLE table_name
ADD column_name datatype
OR

ALTER TABLE table_name


DROP COLUMN column_name
2) DML (Data Manipulation Language): These statements are used to manipulate the data in
records. Commonly used DML statements are Insert, Update, and Delete.
The Select statement is used as partial DML statement that is used to select all or relevant
records in the table.

3) DCL (Data Control Language): These statements are used to set privileges such as Grant
and Revoke database access permission to the specific user.
24) How do we use DISTINCT statement? What is its use?
DISTINCT statement is used with the SELECT statement. If the records contain duplicate
values then DISTINCT is used to select different values among duplicate records.

41 | P a g e
Syntax: SELECT DISTINCT column_name(s)
FROM table_name;
25) What are different Clauses used in SQL?

 WHERE Clause: This clause is used to define the condition, extract and display only
those records which fulfill the given condition
Syntax: SELECT column_name(s)
FROM table_name
WHERE condition;
 GROUP BY Clause: It is used with SELECT statement to group the result of the
executed query using the value specified in it. It matches the value with the column
name in tables and groups the end result accordingly.
Syntax: SELECT column_name(s)
FROM table_name
GROUP BY column_name;
 HAVING clause: This clause is used in association with GROUP BY clause. It is applied
to the each group of result or the entire result as single group and much similar as
WHERE clause, the only difference is you cannot use it without GROUP BY clause
Syntax: SELECT column_name(s)
FROM table_name
GROUP BY column_name
HAVING condition;
 ORDER BY clause: This clause is to define the order of the query output either in
ascending (ASC) or in descending (DESC) order. Ascending (ASC) is the default one but
descending (DESC) is set explicitly.
Syntax: SELECT column_name(s)
FROM table_name
WHERE condition
ORDER BY column_name ASC|DESC;
 USING clause: USING clause comes in use while working with SQL Joins. It is used to
check equality based on columns when tables are joined. It can be used instead ON
clause in Joins.

42 | P a g e
Syntax: SELECT column_name(s)
FROM table_name
JOIN table_name
USING (column_name);
26) Why do we use SQL constraints? Which constraints we can use
while creating database in SQL?
Constraints are used to set the rules for all records in the table. If any constraints get violated
then it can abort the action that caused it.

Constraints are defined while creating the database itself with CREATE TABLE statement or
even after the table is created once with ALTER TABLE statement.

There are 5 major constraints are used in SQL, such as


 NOT NULL: That indicates that the column must have some value and cannot be left
null
 UNIQUE: This constraint is used to ensure that each row and column has unique value
and no value is being repeated in any other row or column
 PRIMARY KEY: This constraint is used in association with NOT NULL and UNIQUE
constraints such as on one or the combination of more than one columns to identify the
particular record with a unique identity.
 FOREIGN KEY: It is used to ensure the referential integrity of data in the table and also
matches the value in one table with another using Primary Key
 CHECK: It is used to ensure whether the value in columns fulfills the specified condition
28) What are transaction and its controls?
A transaction can be defined as the sequence task that is performed on databases in a logical
manner to gain certain results. Operations performed like Creating, updating, deleting records in
the database comes from transactions.

In simple word, we can say that a transaction means a group of SQL queries executed on
database records.

There are 4 transaction controls such as

 COMMIT: It is used to save all changes made through the transaction


 ROLLBACK: It is used to roll back the transaction such as all changes made by the
transaction are reverted back and database remains as before
 SET TRANSACTION: Set the name of transaction
 SAVEPOINT: It is used to set the point from where the transaction is to be rolled back
29) What are properties of the transaction?
Properties of transaction are known as ACID properties, such as
 Atomicity: Ensures the completeness of all transactions performed. Checks whether
every transaction is completed successfully if not then transaction is aborted at the
failure point and the previous transaction is rolled back to its initial state as changes
undone
 Consistency: Ensures that all changes made through successful transaction are
reflected properly on database

43 | P a g e
 Isolation: Ensures that all transactions are performed independently and changes made
by one transaction are not reflected on other
 Durability: Ensures that the changes made in database with committed transactions
persist as it is even after system failure
30) How many Aggregate Functions are available there in SQL?
SQL Aggregate Functions calculates values from multiple columns in a table and returns a
single value.

There are 7 aggregate functions we use in SQL

 AVG(): Returns the average value from specified columns


 COUNT(): Returns number of table rows
 MAX(): Returns largest value among the records
 MIN(): Returns smallest value among the records
 SUM(): Returns the sum of specified column values
 FIRST(): Returns the first value
 LAST(): Returns Last value
31) What are Scalar Functions in SQL?
Scalar Functions are used to return a single value based on the input values. Scalar Functions
are as follows

 UCASE(): Converts the specified field in upper case


 LCASE(): Converts the specified field in lower case
 MID(): Extracts and returns character from text field
 FORMAT(): Specifies the display format
 LEN(): Specifies the length of text field
 ROUND(): Rounds up the decimal field value to a number

37) What is SQL Injection?


SQL Injection is a type of database attack technique where malicious SQL statements are
inserted into an entry field of database such that once it is executed the database is opened for
an attacker. This technique is usually used for attacking Data-Driven Applications to have an
access to sensitive data and perform administrative tasks on databases.

39) What is the difference between SQL and PL/SQL?


SQL is a structured query language to create and access databases whereas PL/SQL comes
with procedural concepts of programming languages.

40) What is the difference between SQL and MySQL?


SQL is a structured query language that is used for manipulating and accessing the relational
database, on the other hand, MySQL itself is a relational database that uses SQL as the
standard database language.

44 | P a g e
42) What is the Cartesian product of table?
The output of Cross Join is called as a Cartesian product. It returns rows combining each row
from the first table with each row of the second table. For Example, if we join two tables having
15 and 20 columns the Cartesian product of two tables will be 15×20=300 Rows.

45) What is the difference between clustered and non-clustered


indexes?
 One table can have only one clustered index but multiple nonclustered indexes.
 Clustered indexes can be read rapidly rather than non-clustered indexes.
 Clustered indexes store data physically in the table or view and non-clustered indexes
do not store data in table as it has separate structure from data row
46) What is the difference between DELETE and TRUNCATE?
 The basic difference in both is DELETE is DML command and TRUNCATE is DDL
 DELETE is used to delete a specific row from the table whereas TRUNCATE is used to
remove all rows from the table
 We can use DELETE with WHERE clause but cannot use TRUNCATE with it
47) What is the difference between DROP and TRUNCATE?
TRUNCATE removes all rows from the table which cannot be retrieved back, DROP removes
the entire table from the database and it cannot be retrieved back.

50) What is Normalization? How many Normalization forms are there?


Normalization is used to organize the data in such manner that data redundancy will never
occur in the database and avoid insert, update and delete anomalies.

There are 5 forms of Normalization


 First Normal Form (1NF): It removes all duplicate columns from the table. Creates table
for related data and identifies unique column values
 First Normal Form (2NF): Follows 1NF and creates and places data subsets in an
individual table and defines relationship between tables using primary key
 Third Normal Form (3NF): Follows 2NF and removes those columns which are not
related through primary key
 Fourth Normal Form (4NF): Follows 3NF and do not define multi-valued dependencies.
4NF also known as BCNF

56) What is Collation?


Collation is set of rules that check how the data is sorted by comparing it. Such as Character
data is stored using correct character sequence along with case sensitivity, type, and accent.

68. What is a primary key?


Ans. A Primary key is a column whose values uniquely identify every row in a table. Primary key
values can never be reused.
69. What are foreign keys?
Ans. When a one table’s primary key field is added to related tables in order to create the

45 | P a g e
common field which relates the two tables, it called a foreign key in other tables.
Foreign Key constraints enforce referential integrity.
70. What is CHECK Constraint?
Ans. A CHECK constraint is used to limit the values or type of data that can be stored in a
column. They are used to enforce domain integrity.
87. What do you mean by ROWID?
Ans. It’s an 18 character long pseudo column attached with each row of a table.
88. Define UNION, MINUS, UNION ALL, INTERSECT ?
Ans. MINUS – returns all distinct rows selected by the first query but not by the second.
UNION – returns all distinct rows selected by either query

UNION ALL – returns all rows selected by either query, including all duplicates.

INTERSECT – returns all distinct rows selected by both queries.

91. What is a composite primary key?


Ans. Primary key created on more than one column is called composite primary key.
108. What is the difference between Having clause and Where clause?
Ans. Both specify a search condition but Having clause is used only with the SELECT
statement and typically used with GROUP BY clause.
If GROUP BY clause is not used then Having behaves like WHERE clause only.
109. What is the difference between Local and Global temporary table?
Ans. If defined in inside a compound statement a local temporary table exists only for the
duration of that statement but a global temporary table exists permanently in the DB but its rows
disappear when the connection is closed.
110. What is CTE?
Ans. A CTE or common table expression is an expression which contains temporary result set
which is defined in a SQL statement.

1) What is Routing Guard in Angular?


Angular’s route guards are interfaces which can tell the router whether or not it should allow
navigation to a requested route. They make this decision by looking for a true or false return
value from a class which implements the given guard interface.

2) What are the differences between AngularJS (angular 1.x) and


Angular (Angular 2.x and beyond)?
Angular and AngularJS is basically a different framework with the same name.
Angular is more ready for the current state of web standards and the future state of the web
(ES6\7, immutiablity, components, shadow DOM, service workers, mobile compatibilty,
modules, typescript and so on and so on... )
Angular killed many main features in AngularJS like - controllers, $scope, directives (replaced
with @component annotations), the module definition, and much more, even simple things like

46 | P a g e
ng-repeat has not left the same as it was.
Also:
1. They added an angular cli.
2. Your angular code is written in ES6 Typescript and it compiles at runtime to Javascript in
the browser.
3. You bind to your HTML similarly like how you would if in an Angular 1 directive. So
variable like $scope and $rootScope have been deprecated.

3) What is a component? Why would you use it?


Components are the most basic building block of an UI in an Angular application. An Angular
application is a tree of Angular components. Angular components are a subset of directives.
Unlike directives, components always have a template and only one component can be
instantiated per an element in a template.
A component must belong to an NgModule in order for it to be usable by another component or
application. To specify that a component is a member of an NgModule, you should list it in the
declarations field of that NgModule.
@Component({selector: 'greet', template: 'Hello {{name}}!'})
class Greet {
name: string = 'World';
}

4) What is the minimum definition of a component?


The absolute minimal configuration for a @Component in Angular is a template. Both template
properties are set to optional because you have to define either template or templateUrl.
When you don't define them, you will get an exception like this:
No template specified for component 'ComponentName'
A selector property is not required, as you can also use your components in a route.

5) What's the difference between an Angular component and


module?
Components control views (html). They also communicate with other components and services
to bring functionality to your app.
Modules consist of one or more components. They do not control any html. Your modules
declare which components can be used by components belonging to other modules, which
classes will be injected by the dependency injector and which component gets bootstrapped.
Modules allow you to manage your components to bring modularity to your app.

6) What is a module, and what does it contain?


An Angular module is set of Angular basic building blocks like component, directives, services
etc. An app can have more than one module.
A module can be created using @NgModule decorator.
@NgModule({

47 | P a g e
imports: [ BrowserModule ],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

7) What is a service, and when will you use it?


Angular services are singleton objects which get instantiated only once during the lifetime of
an application. They contain methods that maintain data throughout the life of an application,
i.e. data does not get refreshed and is available all the time. The main objective of a service is
to organize and share business logic, models, or data and functions with different components
of an Angular application.
The separation of concerns is the main reason why Angular services came into existence. An
Angular service is a stateless object and provides some very useful functions.

8) What is the equivalent of ngShow and ngHide in Angular?


Just bind to the hidden property

9) What are pipes? Give me an example.


A pipe takes in data as input and transforms it to a desired output. You can chain pipes
together in potentially useful combinations. You can write your own custom pipes. Angular
comes with a stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe,
CurrencyPipe, and PercentPipe.
Consider:
<p>The hero's birthday is {{ birthday | date }}</p>
In this page, you'll use pipes to transform a component's birthday property into a humanfriendly date.

10) You have an HTML response I want to display. How do I do that?


The correct syntax is the following:
<div [innerHTML]="theHtmlString"></div>
Working in 5.2.6

11) How can I select an element in a component template?


You can get a handle to the DOM element via ElementRef by injecting it into your component's
constructor:
constructor(myElement: ElementRef) { ... }

13) What is the difference between *ngIf vs [hidden]?


*ngIf effectively removes its content from the DOM while [hidden] modifies the display
property and only instructs the browser to not show the content but the DOM still contains it.

48 | P a g e
14) What is the difference between "@Component" and "@Directive"
in Angular?
Directives add behaviour to an existing DOM element or an existing component
instance.
A component, rather than adding/modifying behaviour, actually creates its own view
(hierarchy of DOM elements) with attached behaviour.

Write a component when you want to create a reusable set of DOM elements of UI with custom
behaviour.

Write a directive when you want to write reusable behaviour to supplement existing
DOM elements.

16) How would you protect a component being activated through the
router?
The Angular router ships with a feature called guards. These provide us with ways to control
the flow of our application. We can stop a user from visitng certain routes, stop a user from
leaving routes, and more. The overall process for protecting Angular routes:
Create a guard service: ng g guard auth
Create canActivate() or canActivateChild() methods
Use the guard when defining routes
// import the newly created AuthGuard
const routes: Routes = [
{
path: 'account',
canActivate: [AuthGuard]
}
];
Some other available guards:
CanActivate: Check if a user has access
CanActivateChild: Check if a user has access to any of the child routes
CanDeactivate: Can a user leave a page? For example, they haven't finished editing a
post
Resolve: Grab data before the route is instantiated
CanLoad: Check to see if we can load the routes assets

17) What are some differences between Angular 2 and 4?


Just to name a few:
Improvements in AOT,
allowing the "else" clause in ngIf,
support for TypeScript 2.1
breaking out the animations package

18) How would you run unit test?

49 | P a g e
The Angular CLI downloads and install everything you need to test an Angular application with
the Jasmine test framework.
The project you create with the CLI is immediately ready to test. Just run this one CLI
command:
ng test

19) What are the differences between Observables & Promises?


1. Promise:- Promises are only called once and It can return only a single value at a time
and the Promises are not cancellable.
2. Observables:- Observables handle multiple values over time and it can return multiple
values and the Observables are cancellable.
3. The Observables are more advanced than Promises.

Both Promises and Observables will help us work with the asynchronous functionalities in
JavaScript. They are very similar in many cases, however, there are still some differences
between the two as well, promises are values that will resolve in asynchronous ways
like http calls. On the other hand, observables deal with a sequence of asynchronous events.
The main differences are listed as below:
promise:
 having one pipeline
 usually only use with async data return
 not easy to cancel
observable:
 are cancellable
 are retriable by nature such as retry and retryWhen
 stream data in multiple pipelines
 having array-like operations like map, filter etc
 can be created from other sources like events
 they are functions, which could be subscribed later on

20) What are differences between Constructors and ngOnInit?


Constructors:-

1. The constructor is a default method runs when component is being constructed.


2. The constructor is a typescript feature and it is used only for a class instantiations and
nothing to do with Angular 2.
3. The constructor called first time before the ngOnInit().

ngOnInit:-

50 | P a g e
1. The ngOnInit event is an Angular 2 life-cycle event method that is called after the first
ngOnChanges and the ngOnInit method is use to parameters defined with
@Input otherwise the constructor is OK.

2. The ngOnInit is called after the constructor and ngOnInit is called after the first
ngOnChanges.

3. The ngOnChanges is called when an input or output binding value changes.

Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the
constructor. The constructor should only be used to initialize class members but shouldn't do
actual "work".

21) What are differences between Components and Directives?


Angular components vs directives

@Components @Directive
1. @Component meta-data annotation is @Directive meta-data annotation is used
used to register the components. to register the directives.
2. The components are used to create UI The directives are used to add behavior to
widgets. existing DOM elements.

3. The components are used to split to The directives are use to design a
application into smaller parts. reusable components.
4. Only one component is used per DOM More than one directive are used per
element. DOM element.
5. In the components, @View, template The directive do not have @View etc.
and templateUrl are mandatory in the
components.

22) Why should `ngOnInit` be used, if we already have a `constructor`?


Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the
constructor. The constructor should only be used to initialize class members but shouldn't do
actual "work".
So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is
better place to "start" - it's where/when components' bindings are resolved.

23) How to bundle an Angular app for production?


 npm install
 npm start. For development. This will create a virtual "dist" folder that will be
livereloaded at your localhost address.
 npm run build. For production. "This will create a physical "dist" folder version than can
be sent to a webserver.

51 | P a g e
24) What is difference between "declarations", "providers" and "import"
in NgModule
 imports makes the exported declarations of other modules available in the current
module
 declarations are to make directives (including components and pipes) from the current
module available to other directives in the current module. Selectors of directives,
components or pipes are only matched against the HTML if they are declared or imported.
 providers are to make services and values known to DI. They are added to the root
scope and they are injected to other services or directives that have them as dependency.

A special case for providers are lazy loaded modules that get their own child
injector. providers of a lazy loaded module are only provided to this lazy loaded module by
default (not the whole application as it is with other modules).

 exports makes the components, directives, and pipes available in modules that add this
module to imports. exports can also be used to re-export modules such as CommonModule
and FormsModule, which is often done in shared modules.
 entryComponents registers components for offline compilation so that they can be used
with ViewContainerRef.createComponent(). Components used in router configurations are
added implicitly.

25) What is Reactive Programming and how to use one with Angular?
Reactive programming is programming with asynchronous data streams. RxJs stands for
Reactive Extensions for Javascript, and it's an implementation of Observables for Javascript. An
Observable is like a Stream (in many languages) and allows to pass zero or more events where
the callback is called for each event. Angular currently uses RxJs Observables in two different
ways:

 as an internal implementation mechanism, to implement some of its core logic


like EventEmitter

 as part of its public API, namely in Forms and the HTTP module

You do not need to know Reactive Programming or RxJS in order to build even the most
complex applications with Angular. It can however make some types of applications easier to
architect.

26) What's new in Angular 6 and why shall we upgrade to it?

 Angular Elements - Angular Elements is a project that lets you wrap your Angular
components as Web Components and embed them in a non-Angular application.

 New Rendering Engine: Ivy - increases in speed and decreases in application size.

52 | P a g e
 Tree-shakeable providers - a new, recommended, way to register a provider, directly
inside the @Injectable() decorator, using the new providedInattribute

 RxJS 6 - Angular 6 now uses RxJS 6 internally, and requires you to update your
application also. RxJS released a library called rxjs-compat, that allows you to bump
RxJS to version 6.0 even if you, or one of the libraries you’re using, is still using one of
the “old” syntaxes.

 ElementRef<T> - in Angular 5.0 or older, is that the said ElementRef had its
nativeElement property typed as any. In Angular 6.0, you can now type ElementRef
more strictly.

 Animations - The polyfill web-animations-js is not necessary anymore for animations in


Angular 6.0, except if you are using the AnimationBuilder.

 i18n - possibility to have “runtime i18n”, without having to build the application once per
locale.

27) What are differences between MOCK VS STUB VS SPY?


A mock is a dummy class replacing a real one, returning something like null or 0 for each
method call. You use a mock if you need a dummy instance of a complex class which would
otherwise use external resources like network connections, files or databases or maybe use
dozens of other objects. The advantage of mocks is that you can isolate the class under test
from the rest of the system.

A stub is also a dummy class providing some more specific, prepared or pre-recorded, replayed
results to certain requests under test. You could say a stub is a fancy mock. In Spock you will
often read about stub methods.

A spy is kind of a hybrid between real object and stub, i.e. it is basically the real object with
some (not all) methods shadowed by stub methods. Non-stubbed methods are just routed
through to the original object. This way you can have original behaviour for "cheap" or trivial
methods and fake behaviour for "expensive" or complex methods.

28) What is TestBed?


The TestBed class is one of the principal Angular testing utilities!

The TestBed class is responsible for configuring and initializing the environment that we are
going to write our tests in by calling TestBed.configureTestingModule.

The TestBed.configureTestingModule is used to define the environment that we want our


component under test to live in.

29) What is Protractor?

Protractor is an end-to-end test framework for Angular and AngularJSapplications. Protractor is


a Node.js program built on top of WebDriverJS. Protractor runs tests against your application
running in a real browser, interacting with it as a user would.

53 | P a g e
32) What is AOT Compilation? - Pros and Cons of Ahead-of-Time!

AOT compilation stands for “Ahead of Time compilation” and it are used to compiles the angular
components and templates to native JavaScript and HTML during the build time instead of run-
time.
The compiled HTML and JavaScript are deployed to the web server so that the compilation and
render time can be saved by the browser. It is the big advantage to improve the performance of
applications.

Advantages of AOT -
1. Faster download: - The Angular app is already compiled so it is faster.
2. Faster Rendering: - If the app is not AOT compiled and the compilation process
happens in the browser once the application is fully loaded. This has a wait time for all
necessary components to be downloaded and then the time taken by the compiler to
compile the app. With AOT compilation, this is optimized.
3. Lesser Http Requests: - It is supporting to the lazy loading. Actually, lazy loading is
great concepts for sending HTTP request to the server. It is minimise the multiple requests
for each associated html and css, there is a separate request goes to the server.
4. Detect error at build time: - In Angular , the compilation happens beforehand and most
of the errors can be detected at the compile time and this process providing us a better
application’s stability.

Disadvantages of AOT -
1. AOT only works only with HTML and CSS and not for other file types. If required other
file types that time we will need to follow the previous build step.
2. We need to maintain AOT version of bootstrap file.

3. We need to clean-up step before compiling.

36) When would you use eager module loading? Or Name and explain
some Angular Module Loading examples

A module can be loaded eagerly, lazily and preloaded. Eager loading is loading modules before
application starts. Lazy loading is loading modules on demand. Preloading is loading modules in
background just after application starts. In lazy loading and preloading, modules are loaded
asynchronously.
The application module i.e. AppModule is loaded eagerly before application starts. But the
feature modules can be loaded either eagerly or lazily or preloaded.
Eager loading: To load a feature module eagerly we need to import it into application module
using importsmetadata of @NgModule decorator. Eager loading is useful in small size
applications. In eager loading, all the feature modules will be loaded before the application
starts. Hence the subsequent request to the application will be faster.
Lazy loading: To load a feature module lazily we need to load it using loadChildren property in
route configuration and that feature module must not be imported in application module. Lazy

54 | P a g e
loading is useful when the application size is growing. In lazy loading, feature module will be
loaded on demand and hence application start will be faster.
Preloading: To preload a feature module we need to load it using loadChildren property and
configure preloadingStrategy property with RouterModule.forRoot. That feature module must
not be imported in application module. When we assign Angular PreloadAllModules strategy
to preloadingStrategy property, then all feature modules configured with loadChildren, are
preloaded. To preload selective modules, we need to use custom preloading strategy. We
should preload only those features which will be visited by users just after application start and
rest feature modules can be loaded lazily. In this way we can improve the performance of our
bigger size application.

37) What are the lifecycle hooks for components and directives?
A component in Angular has a life-cycle, a number of different phases it goes through from birth
to death. We can hook into those different phases to get some pretty fine grained control of our
application.

 constructor This is invoked when Angular creates a component or directive by calling


new on the class.

 ngOnChanges Invoked every time there is a change in one of th input properties of the
component.

 ngOnInit Invoked when given component has been initialized. This hook is only called
once after the first ngOnChanges

 ngDoCheck Invoked when the change detector of the given component is invoked. It
allows us to implement our own change detection algorithm for the given component.

 ngOnDestroy This method will be invoked just before Angular destroys the component.
Use this hook to unsubscribe observables and detach event handlers to avoid memory
leaks.

These hooks are only called for components and not directives.

 ngAfterContentInit Invoked after Angular performs any content projection into the
components view (see the previous lecture on Content Projection for more info).

 ngAfterContentChecked Invoked each time the content of the given component has
been checked by the change detection mechanism of Angular.

 ngAfterViewInit Invoked when the component’s view has been fully initialized.

 ngAfterViewChecked Invoked each time the view of the given component has been
checked by the change detection mechanism of Angular.

39) Could I use jQuery with Angular?

55 | P a g e
You can generally use JQuery in Angular app but it is not good practice to use jquery in
Angular app. It will hamper code modularity in maintenance phases.

Here are the following steps to run or include jQuery into your Angular 6 app:

First install jQuery using npm as follows

npm install jquery — save


Second go to the ./angular-cli.json file at the root of your Angular CLI project folder, and find
the scripts: [] property, and include the path to jQuery as follows

“scripts”: [ “../node_modules/jquery/dist/jquery.min.js” ]
Now to use jQuery anywhere in your application, all you have to do is to import it as follows
in app.component.ts file.

import * as $ from ‘jquery’;

43) What is Zone in Angular?


NgZone is a wrapper around Zone.js which is a library that creates a context around
asynchronous functions in order to to make them trackable. Angular's change detection is
heavily dependent on Zones.

44) Why would you use lazy loading modules in Angular app?
To load a feature module lazily we need to load it using loadChildren property in route
configuration and that feature module must not be imported in application module. Lazy loading
is useful when the application size is growing. In lazy loading, feature module will be loaded on
demand and hence application start will be faster.

const routes: Routes = [


{
path: 'customers',
loadChildren: 'app/customers/customers.module#CustomersModule'
},
{
path: 'orders',
loadChildren: 'app/orders/orders.module#OrdersModule'
},
{
path: '',
redirectTo: '',
pathMatch: 'full'

56 | P a g e
}

46) What does a just-in-time (JIT) compiler do (in general)?


A JIT compiler runs after the program has started and compiles the code (usually bytecode or
some kind of VM instructions) on the fly (or just-in-time, as it's called) into a form that's usually
faster, typically the host CPU's native instruction set. A JIT has access to dynamic runtime
information whereas a standard compiler doesn't and can make better optimizations like inlining
functions that are used frequently.

This is in contrast to a traditional compiler that compiles all the code to machine
language before the program is first run.

48) What is ngUpgrage?


NgUpgrade is a library put together by the Angular team, which we can use in our applications
to mix and match AngularJS and Angular components and bridge the AngularJS and Angular
dependency injection systems.

49) Name some security best practices in Angular

1. To systematically block XSS bugs, Angular treats all values as untrusted by default
(sanitation)

2. Angular templates are the same as executable code: HTML, attributes, and binding
expressions (but not the values bound) in templates are trusted to be safe. To prevent
these vulnerabilities, use the offline template compiler, also known as template injection.

3. Avoid interacting with the DOM directly and instead use Angular templates where
possible.

4. Injecting template code into an Angular application is the same as injecting executable
code into the application. So, validate all data on server-side code and escape
appropriately to prevent XSS vulnerabilities on the server.

5. Angular HttpClient provides built-in support to prevent XSRF attacks on the client side.

Servers can prevent the XSSI attack by prefixing all JSON responses to make them non-
executable, by convention, using the well-known string ")]}',\n". Angular’s HttpClient library
recognizes this convention and automatically strips the string ")]}',\n" from all responses before
further parsing

51) Just-in-Time (JiT) vs Ahead-of-Time (AoT) compilation. Explain the


difference.
JIT - Compile TypeScript just in time for executing it:

57 | P a g e
 Compiled in the browser.

 Each file compiled separately.

 No need to build after changing your code and before reloading the browser page.

 Suitable for local development.

AOT - Compile TypeScript during build phase:

 Compiled by the machine itself, via the command line (Faster).

 All code compiled together, inlining HTML/CSS in the scripts.

 No need to deploy the compiler (Half of Angular size).

 More secure, original source not disclosed.

 Suitable for production builds.

52) Do you know how you can run angularJS and angular side by side?
In order to run both frameworks side-by-side and make components interoperable, the Angular
projects comes with a module ngUpgrade. The module basically acts as an adapter facade, so
we don’t really feel that there are two frameworks running side-by-side.

For this to work, four things need to interoperate:

 Dependency Injection - Exposing Angular services into Angular 1.x components and
vice-versa.

 Component Nesting - Angular 1 directives can be used in Angular 2.x components and
Angular 2.x components can used Angular 1 directives

 Content Projection / Transclusion - Angular 1 components transclude Angular 2.x


components and Angular 2.x component project Angular 1 directives

 Change Detection - Angular 1 scope digest and change detectors in Angular >= 2.x are
interleaved

Here’s what a typical upgrade process would look like:

 Include Angular and upgrade module

 Pick component to upgrade and change its controller and template Angular 2.x syntax
(this is now an Angular 2.x component)

 Downgrade Angular 2.x component to make it run in Angular 1.x app

58 | P a g e
 Pick a service to upgrade, this usually requires little amount of change (especially if
we’re on ES2015)

 Repeat step 2 and 3 (and 4)

 Replace Angular 1 bootstrap with Angular 2.x bootstrap

55) When to use query parameters versus matrix parameters?

 Query parameters: http://example.com/apples?order=random&color=blue

 Matrix parameters: http://example.com/apples;order=random;color=blue

Answer:
The differences between Matrix parameters and Query Parameters are much more than just
convention.

The main differences are:

 urls with query params won't have their response cached by intermediaries/proxies (at
present)

 matrix parameters may appear anywhere in path

 calculating the relative uri is different

 query params are generally abused to add new verbs instead of using existing methods
on resources

matrix parameters are not resources, they are aspects that help reference a resource in an
information space that is difficult to represent within a hierarchy

64) What is the difference between BehaviorSubject vs Observable?


BehaviorSubject is a type of subject, a subject is a special type of observable so you can
subscribe to messages like any other observable. The unique features of BehaviorSubject are:
 It needs an initial value as it must always return a value on subscription even if it hasn't
received a next()
 Upon subscription, it returns the last value of the subject. A regular observable only
triggers when it receives an onnext
 at any point, you can retrieve the last value of the subject in a non-observable code
using the getValue() method.
Unique features of a subject compared to an observable are:

 It is an observer in addition to being an observable so you can also send values to a


subject in addition to subscribing to it.

59 | P a g e
In addition, you can get an observable from behavior subject using the asObservable() method
on BehaviorSubject.
Observable is a Generic, and BehaviorSubject is technically a sub-type of Observable because
BehaviorSubject is an observable with specific qualities.

An observable can be created from


both Subject and BehaviorSubject using subject.asObservable().

The only difference being you can't send values to an observable using next() method.
In Angular services, I would use BehaviorSubject for a data service as an angular service often
initializes before component and behavior subject ensures that the component consuming the
service receives the last updated data even if there are no new updates since the component's
subscription to this data.

65) What is the Angular equivalent to an AngularJS "$watch"


You can use getter function or get accessor to act as watch on angular.

86) What Types of @NgModules?


There are 5 types of NgModules –
1. Features Module
2. Routing Module
3. Service Module
4. Widget Module
5. Shared Module

Features Module – The feature modules are NgModules for the purpose of organizing an
application code.
Routing Module – The Routing is used to manage routes and also enables navigation from one
view to another view as users perform application tasks.
Service Module – The modules that only contain services and providers. It provides utility
services such as data access and messaging. The root AppModule is the only module that
should import service modules. TheHttpClientModule is a good example of a service.
Widget Module - The third party UI component libraries are widget modules.
Shared Module – The shared module allows you to organize your application code. You can put
your commonly used components, directives, and pipes into the one module and use whenever
required to this module.

88) Why you use BrowserModule, CommonModule, FormsModule,


RouterModule, and HttpClientModule?

60 | P a g e
BrowserModule – The browser module is imported from @angular/platform-browser and it is
used when you want to run your application in a browser.
CommonModule – The common module is imported from @angular/common and it is used
when you want to use directives - NgIf, NgFor and so on.
FormsModule – The forms module is imported from @angular/forms and it is used when you
build template driven forms.

RouterModule – The router module is imported from @angular/router and is used for routing
RouterLink, forRoot, and forChild.
HttpClientModule –The HttpClientModule is imported from @angular/common/http and it used
to initiate HTTP request and responses in angular apps. The HttpClient is more modern and
easy to use the alternative of HTTP.

89) What are the differences in NgModules and JavaScript Modules?


The NgModule is a TypeScript class decorated with @NgModule Decorator - is a fundamental
feature of Angular.
JavaScript also has its own module system for managing collections of JavaScript objects. It is
completely different from the NgModule system.
In JavaScript, each file is a module and all objects defined in the file belong to that module. The
module declares some objects to be public by marking them with the export keyword.
Other JavaScript modules use import statements to access public objects from other modules.
The following is an example of specifying an export and import statements -
export class AppComponent {
//...
}

After export your class, you can import that file code in another file.
import { AppComponent } from './app.component';

Both the JavaScript and Angular use modules to organize applications code.

92) What Are Angular Directives?


Angular Directive is a TypeScript class which is declared as a @directive decorator.
The directives allow you to attach behavior to DOM elements and the @directive decorator
provide you an additional metadata that determines how directives should be processed,
instantiated, and used at run-time.
We have 3 types of Directives in Angular -

61 | P a g e
1. Component
2. Attribute Directives
3. Structural Directives
Components - The component is a directive with their own templates and it is responsible for
how a component should be processed, instantiated and used at run-time.
Structural Directives - The structural directive is a directive and it is responsible for change the
DOM layout by adding, removing, and manipulating elements.
The most of the common built-in structural directives are NgIf, NgFor, and NgSwitch.
Attribute Directives - The Attribute directive is a directive and it is responsible for change the
behavior of a specified element or component.

93) What Are Angular Decorators?


The Decorators are functions that modify JavaScript classes and it also used
for attaching metadata to classes.

Directive decorator and metadata Properties -


@Directive({
selector?: string
inputs?: string[]
outputs?: string[]
host?: {...}
providers?: Provider[]
exportAs?: string
queries?: {...}
})

Selector – It is a CSS selector that tells Angular to create an instance of this


component wherever it finds the corresponding tag in template HTML.
Inputs– The list of class property names to data-bind as component inputs
Outputs - The list of class property names that expose output events that
others can subscribe too
Host– These properties use to map the class property to host element
bindings for properties, events, actions, and attributes.
Providers - list of providers available to this component and its children
Queries– To configure queries that can be injected into the component

94) What Is Compiler? Why we need compilation?


The Angular compiler converts our applications code (HTML and TypeScript)
into JavaScript code before browser downloads and runs that code.
The @NgModule metadata plays an important role in guiding the compilation process and also
tells the compiler what components to compile for this module and how to link this module with
other modules.

62 | P a g e
The Angular offers two ways to compile our application code-
1. Just-in-Time (JIT) - JIT compiles our app in the browser at runtime (compiles before
running).
2. Ahead-of-Time (AOT) - AOT compiles our app at build-time (compiles while running).

The JIT compilation is the default when we run the build or serve CLI commands -
ng build
ng serve

The AOT compilation, we append the --aot flags to build or serve CLI commands -
ng build --aot
ng serve --aot

Why we need Compilation in Angular?


We need compilation for achieving a higher level of efficiency, performance improvements,
faster rendering and also sometimes detect template errors earlier in our Angular applications.

1. What Is Entity Framework?


Entity Framework is an additional layer between application and database that
enables the developers to program against the conceptual application model instead
of programming directly against the relational storage schema.

2. What Is Csdl?
Answer :
Conceptual schema definition language (CSDL) is an XML-based language that
describes the entities, relationships, and functions that make up a conceptual model
of a data-driven application. This conceptual model can be used by the Entity
Framework or WCF Data Services.
The metadata that is described with CSDL is used by the Entity Framework to map
entities and relationships that are defined in a conceptual model to a data source.
3. What Is Ssdl?
Answer :
Store schema definition language (SSDL) is an XML-based language that describes
the storage model of an Entity Framework application.
In an Entity Framework application, storage model metadata is loaded from a .ssdl
file (written in SSDL) into an instance of the
System.Data.Metadata.Edm.StoreItemCollection and is accessible by using methods
in the System.Data.Metadata.Edm.MetadataWorkspace class. The Entity Framework
uses storage model metadata to translate queries against the conceptual model to
store-specific commands.

63 | P a g e
4. What Is Msl?
Answer :
Mapping specification language (MSL) is an XML-based language that describes the
mapping between the conceptual model and storage model of an Entity Framework
application.
In an Entity Framework application, mapping metadata is loaded from an .msl file
(written in MSL) at build time. The Entity Framework uses mapping metadata at
runtime to translate queries against the conceptual model to store-specific
commands.
5. What Is Entity Data Model?
Answer :
The Entity Data Model (EDM) is a set of concepts that describe the structure of data,
regardless of its stored form. The EDM borrows from the Entity-Relationship Model
described by Peter Chen in 1976, but it also builds on the Entity-Relationship Model
and extends its traditional uses.
The EDM addresses the challenges that arise from having data stored in many forms.
For example, consider a business that stores data in relational databases, text files,
XML files, spreadsheets, and reports.
This presents significant challenges in data modeling, application design, and data
access. When designing a data-oriented application, the challenge is to write efficient
and maintainable code without sacrificing efficient data access, storage, and
scalability.
When data has a relational structure, data access, storage, and scalability are very
efficient, but writing efficient and maintainable code becomes more difficult. When
data has an object structure, the trade-offs are reversed: Writing efficient and
maintainable code comes at the cost of efficient data access, storage, and
scalability. Even if the right balance between these trade-offs can be found, new
challenges arise when data is moved from one form to another. The Entity Data
Model addresses these challenges by describing the structure of data in terms of
entities and relationships that are independent of any storage schema.
This makes the stored form of data irrelevant to application design and development.
And, because entities and relationships describe the structure of data as it is used in
an application (not its stored form), they can evolve as an application evolves.
6. Which Are The Key Concepts Of Entity Data Model?
Answer :

64 | P a g e
The Entity Data Model (EDM) uses three key concepts to describe the structure of
data: entity type, association type, and property. These are the most important
concepts in describing the structure of data in any implementation of the EDM.
1. Entity Type: The entity type is the fundamental building block for describing the
structure of data with the Entity Data Model. In a conceptual model, entity types are
constructed from properties and describe the structure of top-level concepts, such as
a customers and orders in a business application.
2. Association Type: An association type (also called an association) is the
fundamental building block for describing relationships in the Entity Data Model. In a
conceptual model, an association represents a relationship between two entity types
(such as Customer and Order).
3. Property: Entity types contain properties that define their structure and
characteristics. For example, a Customer entity type may have properties such as
CustomerId, Name, and Address.

7. What Is Model First Approach?


Answer :
A new Model First approach was supported in Visual Studio 2010, which was
released together with the second Entity Framework version (Entity Framework v4).
In Model First approach the development starts from scratch. At first, the conceptual
model is created with Entity Data Model Designer, entities and relations are added to
the model, but mapping is not created.
After this Generate Database Wizard is used to generate storage (SSDL) and
mapping (MSL) parts from the conceptual part of the model and save them to the
edmx file. Then the wizard generates DDL script for creating database (tables and
foreign keys)
If the model was modified, the Generate Database Wizard should be used again to
keep the model and the database consistent. In such case, the generated DDL script
contains DROP statements for tables, corresponding to old SSDL from the .edmx file,
and CREATE statements for tables, corresponding to new SSDL, generated by the
wizard from the conceptual part. In Model First approach developer should not edit
storage part or customize mapping, because they will be re-generated each time
when Generate Database Wizard is launched.
8. What Is Code First Approach?
Answer :
Code First allows you to define your model using C# or VB.Net classes, optionally
additional configuration can be performed using attributes on your classes and

65 | P a g e
properties or by using a Fluent API. Your model can be used to generate a database
schema or to map to an existing database.

9. What Is Deferred Loading(lazy Loading)?


Answer :
When objects are returned by a query, related objects are not loaded at the same
time.
Instead they are loaded automatically when the navigation property is accessed. Also
known as “lazy loading,”

10. What Is Eager Loading?


Answer :
The process of loading a specific set of related objects along with the objects that
were explicitly requested in the query.

11. What Is Conceptual Model?


Answer :
An implementation of the Entity Data Model (EDM), specific to the Entity Framework,
which represents an abstract specification for the data structures that define an
entity-relationship representation of data in the domain of an application.

12. What Is Explicit Loading?


Answer :
When objects are returned by a query, related objects are not loaded at the same
time. By default, they are not loaded until explicitly requested using the Load method
on a navigation property.
13. What Do You Mean By Navigation Property?
Answer :
A property of an entity type that represents a relationship to another entity type, as
defined by an association. Navigation properties are used to return related objects as
an EntityCollection or an EntityReference, depending on the multiplicity at the other
end of the association.
14. What Is Entity Framework Advantage?
Answer :

66 | P a g e
Advantage of using entity framework is to generate the automated code to interact
with data base. Its make your application in fast pace of development.
15. Differences Between Poco, Model First And Data First Approach?
Answer :
Database first:
1. Database create before generation of code.
2. Automated code generation by visual studio.
3. using of T4 template generate the C# code.
4. No much control over the Code.
Code First Approach:
1. Database generated from POCO classes.
2. No automated code generation.
3. Fully control over the code. you need to write your own C# Code.
Model First Approach:
1. Creation of Context and tables using the Designer tool.
2. T4 template will generate the C# code.
3. You have not full control over the code or DB.
4. After creation of tables, once you run application it generate database.

16. What Is Client Wins And Store Wins Mode In Entity Framework
Concurrency?
Answer :
Client and Store wins are actions which we need to take when concurrency happens.
In store Wins, data are loaded into entity objects and in Client wins data will store
from client side to database.

17. Explain What Does .edmx File Contains?


Answer :
.edmx file is an XML file, which declares a conceptual model, a storage model and
the mapping between these models. This file also consists the information that is
used by ADO.NET entity data model designer to render a model graphically. It
consists of all the mapping details of how object maps with SQL tables. It is divided
into three categories SSDL, CSDL, and MSL.

18. How Can You Enhance The Performance Of Entity Framework?

67 | P a g e
Answer :
To enhance the performance of Entity Framework, you have to follow the following
steps
1. Try to avoid to put all the DB objects into one single entity model
2. Disable change tracking for entity if not needed
3. Reduce response time for the first request by using pre-
generating Views
4. If not required try to avoid fetching all the fields
5. For data manipulation select appropriate collection
6. Wherever needed use compiled query
7. Avoid using Views and Contains
8. While binding data to grid or paging, retrieve only required no of
records
9. Debug and Optimize LINQ query

19. Explain Why T4 Entity Is Important In Entity Framework?


Answer :
T4 entity is important in Entity framework as it is the heart of entity framework code
generation. It reads the EDMX XML file and generate C# behind code.

1. What Is Web Api?


Answer :
Unlike WCF service Web API is a framework which is used to build/develop Http
based services.
2. What Is Rest?
Answer :
1. REST stands for Representational state transfer.
2. It is a architectural style, which defines rules for creating scalable
services.
3. REST is works on HTTP protocol using its verbs GET, POST, PUT and
DELETE.
3. Can We Do Unit Test Web Api?
Answer :
Web API can be unit test by using Fiddler tool.
Following is the settings to be updated in Fiddler:
Compose Tab -> Enter Request Headers -> Enter the Request Body and execute.

68 | P a g e
4. Can Web Api Return View In Mvc?
Answer :
We cannot return view from Web API.
5. How To Restrict Access To Methods With Specific Http Verbs In Web
Api?
Answer :
With the help of Attributes(like http verbs) one can implement access restrictions in
Web API.
We can define HTTP verbs as attribute over method to restrict access.
Example :
[HttpPost]
public void SampleMethod(SampleClass obj)
{
//logic
}
6. What Is Web Api Routing?
Answer :
Routing is nothing but pattern matching like in MVC.
All routes will get registered in Route Tables.
Example :
Routes.MapHttpRoute(
Name: "SampleWebAPIRoute",
routeTemplate: “api/{controller}/{id}
defaults: new { id = RouteParameter.Optional}
};
7. Differences Between Wcf And Web Api?
Answer :
WCF :
1. WCF is a framework used for build/develop service oriented
applications.
2. WCF can be consumed by clients which can understand XML.
3. WCF supports wide range of protocols like HTTP, TCP, Named Pipes and
more.
4. For each method there has to be attributes like – “WebGet” and
“WebInvoke”

69 | P a g e
5. For REST service we need to use attribute “WebInvoke”.
Web API:
1. Web API is a framework used to build/develop HTTP based services.
2. Web API is an open source platform.
3. It supports only HTTP protocol.
4. Web API can be hosted in IIS or in application.
5. Unlike WCF Rest we can use full features of HTTP in Web API
6. This returns XML or JSON to client.
8. What Are The Advantages Of Using Rest In Web Api?
Answer :
1. REST used to make less data transfers between client and server.
2. Web API supports HTTP protocol verbs for communication.
9. With Wcf Also You Can Implement Rest, So Why Webapi?
Answer :
3. WCF was brought in to implement SOA, never the intention was to
implement REST.
4. Web API is built from Scratch and the only goal is to create HTTP
services using REST.
10. What Are The Advantages Using Webapi?
Answer :
5. OData support (via Queryable attribute)
6. Content Negotiation
7. Filters
8. Model binding and validation
9. Ability to self host outside of IIS
10. Link generation to related resources that incorporates routing rules
11. Full support for routes/routing
12. Ability to create custom help and test pages using ApiExplorer
11. Differentiate Between Wcf And Web Api?
Answer :
WCF - Windows Communication Foundation(WCF) has been created by Microsoft
with .NET Framework 3.0. It supports SOAP based services. It has compatibility with
HTTP, TCP, UDP, etc. Good for developing secure and interoperable services. Used for
back end purposes.
WEB API - Web API open source framework. It has compatibility with HTTP only. It
has a support for non-SOAP based services. It is very light weight hence good for
developing services for low bandwidth devices. It supports OData. It supports most
of the MVC features. Used for front end purposes.

70 | P a g e
12. How Can We Register Exception Filters?
Answer :
Three options are available to register Exception Filters which are From Action, From
Controller and Global registration.

71 | P a g e

Vous aimerez peut-être aussi