0% found this document useful (0 votes)
22 views

All Qa-1

The document discusses jQuery interview questions and answers. It provides definitions and explanations of common jQuery terms and concepts such as what jQuery is, why it is used, DOM ready event, chaining, callback functions, differences between jQuery and JavaScript, using jQuery in a webpage, and various selectors.

Uploaded by

SHAILESH JORE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

All Qa-1

The document discusses jQuery interview questions and answers. It provides definitions and explanations of common jQuery terms and concepts such as what jQuery is, why it is used, DOM ready event, chaining, callback functions, differences between jQuery and JavaScript, using jQuery in a webpage, and various selectors.

Uploaded by

SHAILESH JORE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 136

JQuery Interview Question-Answer

1. What is jQuery?
 jQuery is JavaScript library.
 jQuery greatly simplifies javascript programming.
 The main advantage of jQuery is it is lightweight, simple and easy to learn.

2. Why use jQuery?


 For perform any task jQuery requires less code as compared to JavaScript.
 It support all web browser, AJAX capabilities, event detection and handling, manipulate
CSS style, and predefined method for create animation.
 Many of the biggest companies on the Web use jQuery, such as: Google, Microsoft and
IBM.

3. Why need Document.Ready event ?


 Document.Ready method allows us to execute a function when document is fully
loaded.

4. What is chaining?
 Chaining are used to run multiple jQuery methods (on the same element) within a single
statement.

5. What is callback function ?


 A callback function is a function passed as a parameter to another function.

6. How JavaScript is differ from jQuery ?


 JavaScript is a language and jQuery is a built in library for JavaScript.

7. Is jQuery a library for client scripting or server scripting?


 Obviously jQuery is a library for client side scripting.

8. What is the basic need to start with jQuery?


 To use jQuery library on your web-page you need to give reference of jQuery library.
1) Include jQuery from a CDN, like Google
2) Local Copy – Download from google and save in our project folder and give
reference.

9. Which is starting point of code execution in jQuery?


 $(document).ready(function( ){ });

10. What is dollar sign ($) in jQuery ?


 Dollar Sign is an alias for jQuery.
 You can write jQuery at the place of $

$.noConflict(); --> noConflict() method releases jQuery control of the $ variable.


11. Can we have multiple document.ready() function on the same page?
 Yes. You can write any number of document.ready() function on the same page.

12. Difference between body onload() and document.ready() function?


 You can have more than one document.ready() function in a page where we can have
only one body onload function.

13. What is a CDN?


 A content delivery network or content distribution network (CDN) is a large distributed
system of servers deployed in multiple data centres across the Internet.
Advantages :
 It reduces the load from your server.
 It saves bandwidth.
 When any user visit on other website it save in browser, as a result next time easily load.

14. How to iterate object in jQuery ?


 We can use each() method to iterate object in jQuery.

15. What are the selectors in JQuery ?


 Selectors are used to select or find the HTML element.
 Some selectors are :
1. class : Represented by single dot.
2. id : Represented by single hatch(Faster selector in jQuery).
3. Element : Represented by single element name.
4. Element with attribute : Represented by single element name with attribute name.
1. What are features in MVC5?

- With MVC 5 there are many important features were introduced. Support for Bootstrap, Attribute
based routing, ASP.NET identity support.

[Please refer http://www.webdevelopmenthelp.net/2014/02/asp-net-mvc3-vs-mvc4-vs-mvc5.html


for details. Interviewer can ask you about explanation on any of the feature you mentioned. ]

2. How request and response occurs in MVC Application?

- Whenever user initiates the request with the help of routing it finds the controller. It creates of
object of that controller and start execution for requested action method. If action method is
returning a ViewResult then it finds appropriate view and returns to the browser. [Please follow
below diagram if interviewer ask you to write a flow. No need to mention entire things he wants
high level things from this pipeline.]

3. What is RouteConfig file?

- In RouteConfig file we defines routes for our application. There is a method called RegisterRoutes
which contains all routings which is configured in Application_Start event of global.asax file.

4. Can we write {controller}/{id}/{action}?

- Yes we can define such routing. But we need to take care for url request.

5. What are filters in MVC?

- Using filters we can add pre and post processing logic for any action methods. We can apply these
filter attributes either on controller or on action methods.

6. How to implement Custom Filters?


- All types of filters in MVC implements interfaces like IActionFilter, IExceptionFilter. If we want to
create custom filters then either we can implement these interfaces or we can override methods
from Filter Attribute classes.

7. How did you implement Authentication and Authorization filters?

- http://www.dotnettricks.com/learn/mvc/custom-authentication-and-authorization-in-aspnet-mvc

8. How you handled global error handling in MVC?

- We can write a custom filter for HandleError attribute or IExceptionFilter and we can provide our
own implementation for OnException method. We can register this custom error filter in FilterConfig
file which will be then applied to all action methods in application or we can apply this class at
controller level or at action method.

9. What is difference between ASP.NET and MVC application?

- There are various differences between ASP.NET and MVC application.

MVC is lightweight compare to ASP.NET.

ASP.NET application we request to a physical file i.e. Web forms whereas in MVC application we
request to a controller action methods.

ASP.NET application uses server controls which makes page heavy but in MVC we use HTML helpers
which are lightweight.

ASP.NET code is tightly bind with code behind file whereas in MVC view and action methods are
separated.

ASP.NET is event based development model whereas MVC is an architectural pattern with Model
Views and Controllers.

10. How to transfer data from View to controller?

- We can use Query string, Hidden fields or form posted values to transfer data from view to
controller.

11. How to transfer data from Controller to View?

- There are multiple ways to transfer data between controllers to view. We can use ViewBag,
ViewData, TempData, Session, strongly typed view depending on scope we want to implement.

12. Can we transfer data from Controller to View using Tempdata?

- Yes we can pass data from Controller to View using Tempdata. We can access Tempdata object in
View.

13. Which version of MVC you have used?

- We have used MVC 4/ MVC 5 in our last project.

14. What is HttpVerbs in MVC?

- HttpVerbs decides the request type whether it is a GET or POST requests. Either we can use
HttpVerbs attribute to specify or we can directly use HttpGet or HttpPost to specify type of request.

15. What is Area? Have you used in your project?


- Yes we have used areas in our project. We created role based areas in our project.

16. What is difference between Html.Textbox and Html.TextboxFor?

- If a view is strongly typed view then we can use Html.TextboxFor which gives us intelligence and it
automatically take id and name with the help of lambda expression we write whereas Html.Textbox
we use in normal views where we have to specify all attribute values separately.

17. Which filters you have used in your project?

- We have used Authorize filter for authentication, HandleError filter for exception handling,
OutputCache filter. We have created custom filters for global error handling. [Please read out how
we create Custom Handle Error filter and use it in application]

18. What is difference between ViewBag and ViewData?

- Both Viewbag and ViewData are used to pass data from controller to view. ViewBag is a dynamic
property collection whereas ViewData is key-value pair collection. We do not have to make explicit
cast while retrieving value from ViewBag but we have to make an explicit cast to retrieve value from
ViewData.

19. Can we create a view based on 2 different models? or Can we create a strongly typed view
based on 2 or more models?

- Yes we can create a view based on multiple models. There are various way to achieve this. We can
use ViewBag, ViewData, PartialViews, TempData, ViewModel, Tuple to achieve this scenario. Most
preferred way is using ViewModel.

[Please refer - https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-


View-in-MVC]

20. What is routing in MVC?

- Routing helps to map a requested url to controller action methods.

21. How to configure routing?

- There are 2 different ways to configure routing

a. We can configure in RouteConfig file.

b. We can use Route attribute to define routing.

22. Is there any other way to configure route except adding in RoutConfig file?

- Yes. We can configure routing using Route attribute also. We can apply this attribute either on
action method or on controller.

23. How can we create multiple routings in RouteConfig file?

- We can use MapRoute method and configure more than one routes. We have to mandatory
provide name and url parameters to MapRoute method.

24. What is Route attribute?

- Using Route attribute we can configure routings in MVC application. We can use Route attribute on
action method or on controller level also.
25. What is ActionResult?

- ActionResult is used to return objects from an action method. ActionResult is abstract class which
has several derived types like ViewResult, ContentResult etc.

26. What are different Action Results in MVC?

- There are around 12 to 13 different types of ActionResults. Depending on the returned output we
can use any type from these lists. Available types are like ContentResult, EmptyResult, JsonResult,
ViewResult, JavascriptResult and so on. [If he ask you all then tell him entire list or else no need.]

27. What is JSON?

- JSON is Javascript Object Notation. Which is lightweight compare to XML. If we are calling any
service or method through AJAX call then it is good practice to use JSON to transfer objects.

28. What are filters and sequence of execution of those filters?

- Filters are use to execute logic before and after execution of an action method. Filters are broadly
categorized in 4 categories –

AuthenticationFilter, ActionFilter, ResultFilter and ExceptionFilter.

29. How to transfer data from - M to C, C to V, V to C?

- To transfer data from controller to view we can use ViewBag, ViewData, Tempdata, Session
variables and to transfer data from view to controller we use Query string, Hidden fields or form
posted values.

30. What is AJAX? can you write a syntax for AJAX Call?

- AJAX is asynchronous Javascript. Using AJAX we can call server code without reloading page.

Syntax:

$.ajax({

url: ,

t pe: ,

data: ,

success:function(){},

error:function(){}

});

31. What is ViewModel?

- ViewModel allows us to create a single entity from one or more different entities using which we
can render more models in a view. We can create a strongly typed view based on more than one
models.

32. Is there any other ways to transfer more than one models to a view?
- Yes. There are various way to achieve this. We can use ViewBag, ViewData, PartialViews,
TempData, Tuple to achieve this scenario. Most preferred way is using ViewModel.

[Please refer - https://www.codeproject.com/Articles/1108855/ways-to-Bind-Multiple-Models-on-a-


View-in-MVC]

33. How do you maintain security in your project?

- We have used form based authentication and SSL to provide security in our application.

34. I have one view and that view have one submit button, if I click on that submit button how
execution happen in MVC?

- This request will be a post request. This requests reaches to Routing Engine and based on the
parameters it selects an action method of a controller. Controller takes help of model for any
business logic or data. If action method is returning any view or any other result that will get
returned to the client.

35. What are different client side state management techniques?

- In client side state management techniques we have Query string, Hidden field, Cookies.

36. What is ViewBag, ViewData and TempData?

- These are the techniques to manage state of a MVC application.

ViewBag is a dynamic property collection and ViewData is a key value pair dictionary collection both
are used to pass data from controller to view.

TempData is a dictionary which can be used in subsequent requests.

37. Explain Tempdata and it methods?

- Tempdata is used to store the data and transfer to subsequent requests. TempData value is cleared
after subsequent requests completes. There are Keep and Peek methods which we can use to retain
value in TempData after end of subsequent request also. Keep() method preserves the value for next
request. Peek() method returns TempData value without clearing it from the memory.

38. What are action filters?

- Action filters are used to execute any logic pre and post execution of any action methods. There are
different types of filters available in MVC like AuthorizationFilter, ActionFilter, ResultFilter and
ExceptionFilter.

39. What is Authorize attribute?

- Authorize attribute is used to implement AuthorizationFilter to any action method. Using Authorize
attribute we can restrict or allow any user to access the action method.

40. Explain Exception filter?

- Using ExceptionFilter we can achieve exception handling in MVC. There is an attribute called
HandleError which we can use to implement error handling which reduces efforts in writing try catch
block in each and every action methods.
41. What is MVC? and its Architecture?

- MVC is a architectural pattern to design web applications. In MVC, M stands for Model, C stands for
Controller and V stands for View. Every component has their own responsibilities. Model handles
business logic and provides data to controller and view. View is used to render HTML. Controller
handles user requests.

42. How to pass data from C to V, V to C and C to C?

- Already done.

43. How you validate if UserName is exists in DB or not?

- There is one attribute called RemoteAttribute in MVC which we can use to validate if UserName is
exists in DB or not. RemoteAttribute works with the help of AJAX call. It validates the data against
database in asynchronous manner without reloading a page.

44. Write a syntax for AJAX Call?

- Refer question 30.

45. Which grid you have used to display records in MVC?

- We have used Grid.Mvc nugget package to display records and used bootstrap to control over its
styling. [Refer - https://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-grid-in-mvc-
using-grid-mvc/]

46. What are types of results in MVC?

- There are around 12 to 13 results are there in MVC. ActionResult is base type for all result classes in
MVC. Results classes are available like ViewResult, ContentResult, EmptyResult, JsonResult and so
on.

47. What are attributes?

- Attributes are used to add declarative information to a class or a method. In MVC all validations we
perform using attributes, all filters are attributes.

48. How you maintained session in your MVC project?

- To maintain session we have used ViewBag, ViewData, TempData, Session variables. Depending on
scope we have used these options one over another.

49. What is difference between Tempdate and Session variable?

- TempData is available only till next subsequent request but Session variable is available till the
session gets expire for that user. TempData internally gets stored in session variable. In general, to
store messages like validation messages or error messages we use TempData and the data which we
want to store for entire lifetime of application then we can use Session variable.

50. Write a syntax for AJAX call?

- Refer question 30.

51. Do you no any aggregate syntax to call AJAX?


- Yes. MVC provides us an aggregate syntax to implement AJAX. Using @AJAX.ActionLink we can
write ajax call syntax.

[If syntax asked:

@AJAX.ActionLink Link Te t , Action Method , new Aja Options {

HttpMethod= GET , OnBegin= , On“uccess=

});

52. Which version of MVC you have worked upon?

- I have worked on MVC 4 in my last project.

53. What are security threats in application? What is cross site scripting (CSS attack)?

- Security threats means a way to access our application by any anonymous user to perform any
unauthorized activities which can harm to application data. There are lot of security threats and
there are ways to prevent them. Cross Site Scripting attack is an attack where a user can inject any
script through textbox or textarea and he can execute those unwanted scripts. We can prevent XSS
attack by giving proper validations against these input fields.

54. What is Anti Forgery Token?

- AntiForgeryToken validates a POST requests if it is coming from the same user or not. Using
AntiForgeryToken we can prevent Cross Site Request Forgery attack.

55. Write a code that you done for authentication and authorization in your MVC project?

- Refer question 7.

56. Do you know unit testing?

- Yes. I know unit testing I have used nUnit framework to perform unit testing for modules in my
project.

57. If I have one view which has a button and a div tag. I have created a partial view. Now on click
on that button this partial view should get rendered in div tag. Tell me flow how will you write
code for this.

- I will write an AJAX call to implement this. I can achieve this in 2 ways writing an JQuery AJAX call or
using MVC AJAX helper method. Firstly I will write an action method which returns me partial view.
Then on the main view I will call this action method using AJAX.ActionLink method and I will set
UpdateTargetId parameter to div id.

58. How view model works? If I have to show 3 models on single view how will you achieve that.

- Using ViewModels we can create a stringly typed view based on multiple models. I will create a
view model and I will write all required models as properties inside this class. I will create a strongly
typed view based on this ViewModel.

59. How partial view get rendered on main view?


- There are various ways to render a partial view on main view. We can use Partial, RenderPartial or
RenderAction methods to render partial view on main view.

60. Suppose I have 2 buttons on a view lets say Add and Clear. Then how will you write events and
identify that which button is clicked?

- I will use jquery selectors to write events for these two buttons. If required write action methods
and I will call those action methods using AJAX call.

61. I have 20 views that needs to be parsed using json object & service is called using ajax. How
you will do that.

- No idea if the question is written correctly.

62. Let’s say I want to display 1000 records on my site. How will you show that?

- I will implement pagination to show 1000 of records on a page. In MVC we can use PagedList
package to achieve pagination funcitonality.

63. How the state is maintained in MVC?

- There are 2 different techniques to maintain states in MVC. We can use HiddenFields, Cookies,
QueryString which are client side techniques. We can use ViewBag, ViewData, TempData, Session,
Application and Cache variables which are server side techniques.

64. Whether MVC is different than ASP.NET?

- Refer Question 9.

65. What is Razor engine?

- Razor engine is introduced with MVC. Using Razor engine we can create views like cshtml or
vbhtml. Wherein we can write both html and C# code. If we want to switch from html to C# code we
just have to use @ symbol and we can start writing C# code. Apart from this there helper methods
which helps us to create html controls.

66. Explain lifecycle of MVC application?

- Refer Question 2.

67. What is attribute routing?

- Attribute routing is a new feature introduced with MVC5 where we can use Route attribute to
define routings for our application. Before Route attribute we used to define convention based
routings in RouteConfig file. We can use Route attribute on controller or action method levels.

68. What are partial views and their use?

- Partial views are used to write re-usable views. Which can minimize the complexity of views. We
can create a partial view can we can use it on multiple views.

69. Can one partial view called from another partial view?

- Yes one partial view can call another partial view.

70. What is GET and POST request?


- These are the type of requests which user can perform against our application. In general, If user is
requesting to retrieve some data we refer this method as GET request. By default the initial request
is a get request. If a user wants to post some data to server we consider this request as POST
request. There are HttpVerbs which we use to define type of request.

71. Can one view have 2 submit buttons?

- Yes one view can have two submit buttons. On clicking on those submit button respective action
methods are called which are defined with form tag.

72. What is difference between ActionResult and ViewResult?

- ActionResult is base type for all result classes whereas ViewResult is one implementation of
ActionResult. We can return any data from an action method with ActionResult. If we want to return
a view from action method I can use both ViewResult.

73. Where we do validations in MVC?

- We do all validations in models using validation attributes. All validation specific attributes are
define in System.ComponentModel.DataAnnotations.

74. What is ModelBinder in MVC?

- ModelBinder helps to bind posted values to an action method models. ModelBinders take the data
from Value Providers to create an object. There are various value providers like FormValueProvider,
QueryStringProvider, JsonValueProvider.

75. Have you used cookies in your project?

- Yes we have used cookies to store some non-critical data of user which we had to use in multiple
pages.

76. If you use Area then how the url is displayed?

- By default our url is like domain/controller/action but with area the url is changes to
domain/areaname/controller/action.

77. Which control you have used to display images in your project?

- We have created custom helper class to display images in our application.

78. Can I call more than one action methods at same time in MVC?
[https://stackoverflow.com/questions/10915485/how-to-call-multiple-actions-in-view-in-asp-net-
mvc]

- Yes we can call more than one action methods at same time. We can write to action methods
which are returning me a partial views. Then I can use RenderAction method on main view which will
call all respective action methods.

79. How to call a action method without refreshing a page?

- We can AJAX to call action method without refreshing a page. Refer Question 30.

80. Can we write multiple paths in RouteConfig file?

- Yes. We can define multiple routings in RouteConfig file. We have to make sure while giving name
parameter. Because name should be different for all defined routings.
81. What is difference between Partial and RenderPartial?

- Both the methods are use to render partial view on main view. Partial method returns
MvcHtmlString where as RenderPartial method returns void. If we want to make some changes in
partial view response then we can use Partial method or else we can use RenderPartial method.
RenderPartial method performs better because it directly render response to output stream.

82. What is RenderAction method? When it is used?

- RenderAction method used to render partial view on main view. If there is an action method which
is returning a partial view then I can use RenderAction method to call that action method to render
partial view on main view.

83. What is purpose of OutputCache filter?

- OutputCache attribute is used to implement caching in MVC. If we want to perform page level or
fragment level caching we can use OutputCache attribute with appropriate action methods. It is
somewhat similar to OutputCache directive in ASP.NET

84. What is HandleError attribute?

- Using HandleError attribute we can do error handling in MVC application. Instead of writing try
catch block in each and every action method we can use HandleError attribute to achieve error
handling.

85. How we do error handling in MVC?

- Refer question 84.

86. What will happen if I have used HandleError attribute and try catch block both in an action
method?

- It will not give me any compile time error but the error will be handled by catch block in that case.

87. I have 2 dropdown lists one is for state and other for city. If I select state all cities get shown in
city dropdown list. How will write code for this.

- I will create a ViewModel which will have List of State and City properties. I will add action method
to controller and retrieve data for states from model. For this action method I will add a strongly
typed view using ViewModel. On this View I will 2 dropdownlist with the help of html helpers.
Initially I will disable city dropdownlist. I will add onchange method to state dropdownlist. If user
change state then I will write AJAX call to fetch and bind city data to city dropdownlist.

88. I have a textbox, button and label on a page. If you click on button entered text should be
displayed on label. Write a code for this.

- I will write an action method with parameter name same as textbox name. Then I will make a AJAX
call to action method on click of button. OnSuccess event I will bind response to label. If we don’t
have to hit to server then we can easily achieve this functionality using javascript code writing a
simple javascript function or jQuery selector and event.

89. How to overload action methods? [This question can be asked with 2 action methods]
- I will use ActionName attribute where I will give same name which is used to make a request to
that action method and while writing actual method name I will write different name there. So both
methods can be called with same request with different request type.

90. What are different types of authentication?

- There are 3 different types of authentication Windows Authentication, Forms Authentication and
Passport Authentication. We have used Forms Authentication in our project. A login page where
user can provide credentials to validate.

91. What is bundling and minification?

- Bundling and minification are techniques to improve performance of web site. Basically if we have
multiple javascript files, css files calls on a page then we can club them using bundling to make a
single request for multiple files. On other hand minification is process of compressing js or css files
which actually does 3 things it removes all comments, it removes all new lines and blank spaces and
it shorthand the names of variables and methods. Which reduces the file size.

92. How to return empty string from a action method?

- We can use EmptyResult to return empty value from an action method.

93. How to return string from a action method?

- We can use ContentResult to return a string from an action method.

94. What is layout in MVC? what is purpose of layouts?

- Layouts in MVC is very similar to Master pages in ASP.NET. Using Layouts we can maintain
consistent look and feel of any website. We can have multiple layouts in a single application and we
can include them on a view based on any condition.

95. Can we have more than one layouts in MVC? How will you assign them to views in case of
multiple layouts?

- Yes we can have more than one layouts in single application. We can assign them on view through
ViewStart file or we can assign them on individual views also. We can give any condition to check for
assigning layout to any view.

96. I want to prevent action method to be called with URL?

- If we have written any action method which is public and we want to restrict it to call with an url
then we can mark that method as ChildActionOnly attribute. This method will not be called from
browser but we can call it as child request. We can make a call to this action method using Action()
or RenderAction() methods.

97. I have a textbox, I want to restrict its character limit to 10 characters? How you will achieve
this?

- We can use StringLength attribute on model property to do this type of validation.

98. I have a textbox, I want to allow a user to enter there valid date? How can I validate it?

- We can use DataType attribute on that field to do this validation. We can specify DataType.Date to
this attribute as parameter.
99. How to consume bootstrap in MVC application?

- We can include all bootstrap files like bootstrap.css, bootstrap.js and jquery.js on our layout view
using cdn or we can download and refer them. Then we can set bootstrap classes to any controls
with our helper methods using htmlAttributes property.

100. What is difference between MVC 4 and MVC 5?

- In MVC 4 new features introduced like WEBAPI, Bundling and Minification support, support for
adding controllers to other folders also. In MVC 5, built in support for bootstrap, attribute based
routing, ASP.NET identity.
SQL Interview Question-Answer
1. What are different types of SQL Commands? Or Explain DDL, DML, TCL Commands.
- There are different commands which we use to communicate with the database to perform
specific tasks.
Data Definition Language (DDL) –
These SQL commands are used for creating, modifying, and dropping the structure of
database objects. (i.e. affects on schema or structure)
These commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.
Data Manipulation Language (DML) –
These SQL commands are used for storing, retrieving, modifying and deleting data.
(i.e. affects on data)
These commands are SELECT, INSERT, UPDATE, and DELETE.
Transaction Control Language (TCL) –
These SQL commands are used for managing changes affecting the data.
These commands are COMMIT, ROLLBACK.
Data Control Language (DCL) –
These SQL commands are used for providing security to database objects.
These commands are GRANT and REVOKE.

2. Difference between Delete, Truncate and Drop commands?


Delete
- Delete is a DML command.
- The DELETE command is used to remove rows from a table.
- A WHERE clause can be used to only remove some rows if no WHERE condition is specified, all
rows will be removed.
- We can undo the delete operation by using ROLLBACK transaction command.
- This operation causes all DELETE Triggers to fire on a table.

Truncate
- TRUCATE is a DDL command and it is faster.
- TRUNCATE removes all rows from a table.
- The operation cannot be rolled back and no triggers will be fired.
- Truncate command also reset identity.
Drop
- Drop is a DDL command.
- The DROP command removes a table from the database.
- All the tables' rows, indexes and privileges will also be removed.
- No DML triggers will be fired.
- The Drop operation cannot be rolled back.

[Reason why Truncate is faster ? :When you type DELETE, all the data get copied into the Rollback
Tablespace first then delete operation get performed. That s why when you type ROLLBACK after
deleting a data ,you can get back the data and this process take time. But when you type TRUNCATE,
it removes data directly without copying it into the Rollback Tablespace. That s why TRUNCATE is
faster. Once you Truncate you can't get back the data.]

3. What is difference between Primary key and Unique key?


- Both unique key and Primary key are used to enforce uniqueness in the column records.
- We can find 2 differences in both the keys :
I. We can have a single Primary across the table whereas we can have multiple Unique Key
across the table.
II. Primary Key does not allow NULL value whereas Unique key allows a single NULL value.

4. What is cascading referential integrity?


- If you delete or update records in primary key table and there is dependent records in foreign
key table then cascading referential integrity comes in picture.
- We have the following options when setting up Cascading referential integrity constraint
A. No Action:
This is the default behavior.
It will not allow to delete or update record from primary key table.
B. Cascade:
It will delete or update records from primary key table as well as from foreign key table.
C. Set NULL:
It will delete or update records from primary key table and set null value in foreign key
table.
D. Set Default:
It will delete or update records from primary key table and set default value in foreign key
table.

5.What is composite key in SQL?


- A primary key that is made by the combination of more than one column is known as a
composite key.
- That can be used to uniquely identify each row in the table when the columns are combined
uniqueness is guaranteed, but when it taken individually it does not guarantee uniqueness.
- Sometimes more than one attributes are needed to uniquely identify an entity.
6. Can we insert identity column value explicitly? If yes, then how?
- Yes. We can explicitly insert identity value whenever required.
- We can use Identity_Insert to achieve this.

SET IDENTITY_INSERT tblName ON

7. What are different way to get last generated identity column value?
- There are three ways to fetch last generated identity column value.
SCOPE_IDENTITY() –
Returns the last identity value that is created in the same session and in the same scope.
@@IDENTITY –
Returns the last identity value that is created in the same session and across any scope.
IDENT_CURRENT('tblName') –
Returns the last identity value that is created for a specific table across any session and any
scope.

8. What will be the value of identity column value if all rows deleted from the table? Will it reset
to default values automatically? If No then, How to reset identity column seed and increment
value to default values?
- If all rows get deleted from table but still we able to see last generated identity value.
- We can reset this identity column value to default value by using DBCC CHECKIDENT command.

DBCC CHECKIDENT(tblName, RESEED, 0)

9. What is Normalization in SQL? Why do we need of Normalization? What are different forms of
Normalization? Explain 1st , 2nd and 3rd Normal form.
- Database normalization is the step by step process to design a better database.
- Remove duplication (redundancy)

1NF
1. The data in each column should be atomic. (There should not be comma separated values).
2. The table does not contain any column repeating groups.
3. Every record should identify uniquely (i.e. every record should have primary key).

2NF
1. The table satisfy all the conditions of 1NF.
2. Identify groups and split into multiple tables.
3. Create relationship between these tables using foreign keys.

3NF
1. The table satisfy all the conditions of 1NF and 2NF.
2. Remove all columns (attributes) that are not fully dependent upon the primary key.
10. Difference between Where and Having clause?
- WHERE clause can be used with – Select and Update statements, where as HAVING clause can
only be used with the Select statement.
- WHERE filters rows before aggregation (GROUPING) whereas HAVING filters groups after the
aggregations are performed.
- Aggregate functions cannot be used in the WHERE clause, unless it is in a sub query contained in
a HAVING clause whereas aggregate functions can be used in HAVING clause.

11. What is Join ? What are the different types of joins available in SQL? Explain them.
- JOINS are used to retrieve data from two or more tables based on logical relationships between
these tables.
- Basically there are 3 types of joins available in SQL.
1. Inner Join
2. Outer Join which again classified to 3 subtypes
A. Left Outer Join
B. Right Outer Join
C. Full Outer Join
3. Cross Join

Inner Join –
Inner joins returns only the common records from both the tables.

Left Outer Join –


Left outer join returns common records from both tables as well as uncommon records from left
table.

Right Outer Join –


Right outer join returns common records from both tables as well as uncommon records from
right table.

Full Outer Join –


Full outer join returns common and uncommon records from both tables.

Cross Join –
Cross join returns Cartesian product of the tables involved in the join.

12. What is self join? Can you write a query using self join with one scenario?
- Joining a table with itself is called as SELF JOIN.
- SELF JOIN is not a different type of JOIN.
- It can be classified under any type of JOIN - INNER, OUTER or CROSS Joins.
13. What are different ways to replace NULL values?
- We can replace NULL value using 3 different options :
A. Using ISNULL function (refer Question No 12 for query)
B. Using case statement(refer Question No 12 for query)
C. Using Coalesce() function - COALESCE() returns the first Non NULL value.
[Please prepare for the syntax also]

14. What is difference between Union and Union ALL ?


- UNION and UNION ALL are used to combine the result-set of two or more SELECT queries.
- For UNION and UNION ALL to work, the Number, the Data types, and the order of the columns
in the select statements should be same.
- UNION removes duplicate rows and gives distinct sort whereas UNION ALL does not that s why
UNION ALL is much faster than UNION

15. Difference between Join and Union?


- JOINS and UNIONS are different things.
- UNION are used to combine the result-set of two or more SELECT queries into a single result-set
whereas JOINS are used to retrieve data from two or more tables based on logical relationships
between the tables.
- In short, UNION combines rows from 2 or more tables whereas JOINS combine columns from 2
or more table.

16. What is a sub query? What are its various types? Explain Correlated and Non Correlated Sub
query?
- A subquery is nothing but the simple select query that returns a single value and can be nested
inside a SELECT, UPDATE, INSERT, or DELETE statement.
- Subqueries are always enclosed in parenthesis called inner queries and the query containing the
subquery called outer query.
- There are two types of subqueries :

Non Correlated Sub Query :

- Outer query depends on inner query.


- Inner query runs first.
- Inner query executes once.

Correlated Sub Query :

- Inner query depends on outer query.


- Outer query runs first.
- Inner query runs multiple times till the records are there in outer query.
17. What are stored procedures? Explain its advantages?
- A stored procedure is group of T-SQL (Transact SQL) statements.
- If we have a situation, where we can write the same query again and again then we can save
that specific query as a stored procedure and call it just by its name.

Advantages :
1. Execution plan retention and reusability - Stored Procedures are compiled and their
execution plan is cached and used again, when the same SP is executed again. Although
adhoc queries also create and reuse plan, the plan is reused only when the query is textual
match and the datatypes are matching with the previous call. Any change in the datatype or
you have an extra space in the query then, a new plan is created.

2. Reduces network traffic - You only need to send, EXECUTE SP_Name statement, over the
network, instead of the entire batch of adhoc SQL code.

3. Code reusability and better maintainability - A stored procedure can be reused with
multiple applications. If the logic has to change, we only have one place to change, where as
if it is inline sql, and if you have to use it in multiple applications, we end up with multiple
copies of this inline sql. If the logic has to change, we have to change at all the places, which
makes it harder maintaining inline sql.

4. Better Security - A database user can be granted access to an SP and prevent them from
executing direct "select" statements against a table. This is fine grain access control which
will help control what data a user has access to.

5. Avoids SQL Injection attack - SP's prevent sql injection attack.

18. Write SQL statement to call a Stored Procedures with Return value.
- Let s say there is stored procedure usp_PersonIdByName .
- We can call this procedure as :

Declare @Id int


Execute @Id = usp_PersonNameById A iket
Print @Id
19. Write SQL statement to call a Stored Procedures with Output parameter.
- Let s say there is stored procedure usp_PersonNameById with @Name output parameter. We
can call this procedure as :

Declare @Name varchar(50)


Execute usp_PersonNameById 2, @Name Out
Print @Name

20. What is difference between Return values and Output Parameter in Stored Procedures?
- Using return values, we can return only one value of type integer whereas output parameters
can return multiple values of any type.
- We always prefer, using output parameters over return values.

21. What is difference between Cast and Convert functions?


- To convert one data type to another, CAST and CONVERT functions can be used.
- CONVERT() function has an optional style parameter whereas CAST() function lacks this
capability.
- Convert provides more flexibility than Cast. For example, it's possible to control how you want
DateTime datatypes to be converted using styles with convert function.
- Cast is based on ANSI standard and Convert is specific to SQL Server. So, if portability is a
concern and if you want to use the script with other database applications, use Cast().

22. What are deterministic and non-deterministic functions in SQL?


- Deterministic functions always return the same result any time they are called with a specific set
of input values.
Examples: Sum(), AVG(), Square(), Power() and Count()
- Nondeterministic functions may return different results each time they are called with a specific
set of input values.
Examples: GetDate() and RAND()

23. What is RAND() function? What if you pass it a parameter e.g. RAND(1) ?
- Rand() function is a Non-deterministic function i.e. every time called gives new value between
0 and 1.
- But if we provide the seed value, the function becomes deterministic, as the same value gets
returned for the same seed value.
24. What are functions in SQL? What are different types of functions? Explain.
- Functions are block of SQL statement which are used to perform some computational logic.
- There are 3 different types of functions are available in SQL :

1. Scalar Function :
- Scalar functions always return a single scalar value.
- The returned value can be of any data type except text, ntext, image, cursor, and
timestamp.

2. Inline Table Valued Function :


- The Inline Table Valued function returns a table but we cannot customize the schema of
returned table.
- Inline table valued function cannot have begin and end body.

3. Multi Statement Table Valued Function :


- The multi statement table valued function returns a table and we can customize the
schema of returned table.
- The multi statement table valued function can have begin and end body.

25. What are differences between Stored Procedures and Functions?


- Store procedures are used for business logic (Insert, Update, Delete on Records) whereas
Functions are used for computational logic(Calculations).
- Store procedures cannot call in select statement whereas Functions can call in select statement.
- We can do error ha dli g i Store procedures whereas we ca t do error ha dli g i Fu ctio s.
- We ca i ple e t tra sactio i Store procedures whereas we ca t i ple e t tra sactio i
Functions.
- We can create temporary tables inside Store procedure whereas we ca t create te porary
tables inside Functions.
- We need not to write return statement in Store Procedure whereas it is compulsory to write
return statement inside Function.
- Store procedure can call Store procedure, Store procedure can call Function whereas Function
can call Function but Function can not call Store procedure.

26. What are temporary tables ? What are different types.


- Temporary tables are just like the permanent tables.
- Temporary tables get created in the TempDB and automatically deleted when the session
created temporary table gets closed.
- In SQL Server, there are 2 types of Temporary tables –
1. Local Temporary tables
2. Global Temporary tables.
Difference Between Local and Global Temporary Tables:
1. Local Temp tables are prefixed with single pound (#) symbol whereas global temp tables are
prefixed with double pound (##) symbols.
2. SQL Server appends some random numbers at the end of the local temp table name whereas
this is not done for global temp table names.
3. Local temporary tables are only visible to that session of the SQL Server which has created it,
whereas Global temporary tables are visible to all the SQL server sessions.
4. Local temporary tables are automatically dropped, when the session that created the
temporary tables is closed whereas Global temporary tables are destroyed when the last
connection that is referencing the global temp table is closed.

27. What are table variables?


- Table variable is a special data type that can be used to store a result set for processing at a later
time.
- table is primarily used for temporary storage of a set of rows returned as the result set of a
table-valued function.
- Functions and variables can be declared to be of type table. table variables can be used in
functions, stored procedures.
- Syntax if interviewer ask to write :
DECLARE @userData TABLE(
name varchar(30) NOT NULL,
City varchar(30) NOT NULL
);

INSERT INTO @userData


SELECT name, city FROM Employees

28. What is CTE in SQL? Can you write a syntax to create a CTE?
- CTE means common table expression.
- A CTE is a temporary result set, that can be referenced within a SELECT, INSERT, UPDATE, or
DELETE statement that immediately follows the CTE.

Syntax :
WITH cte_name (Column1, Column2, ..)
AS
( CTE_query )
29. What are differences between Temporary tables, Table Variables and CTE?
- Temporary tables can be stored in TempDB whereas Table variables can be stored in memory
but if there is a memory pressure table variables can be stored in TempDB.
- Temporary tables participates in transaction whereas Table variables does not participate in
transaction this makes table variable faster than a temporary table.
- You can not pass Temporary table as parameter whereas you can pass Table variable as
parameter to store procedure and function.
- A temporary table can have indexes, whereas a table variable can only have a primary index.

30. What is difference between INSERT INTO and SELECT INTO statements?
- Both the statements are used to copy data from one table to another table.
- For INSERT INTO statement it is mandatory to create the table and then fire insert into query
whereas for SELECT INTO statement table creation is not needed this query automatic generates
the table and copy the data.

Syntax for INSERT INTO :

- Insert into tblName values col Value, col Value,…

Or
-
INSERT INTO @targetTblName
SELECT col1, col2 FROM sourceTblName
[We need to create @targetTblName with required columns before firing this query otherwise it will going
to through error.]

Syntax for SELECT INTO :


SELECT col1, col2 INTO targetTblName FROM sourceTblName
[This query automatically generates targetTblName with copied columns and data.]

31.
What are Indexes? Types of Indexes? Advantages and Disadvantages of Indexes?
-Indexes are used by queries to find data from tables quickly.
-Indexes are created on tables and views.
-The existence of the right indexes, can drastically improve the performance of the query.
-If there is no index to help the query then the query engine checks every row in the table
from the beginning to the end this is called as Table Scan and table scan is bad for performance.
- There are 2 types indexes in SQL :

1. Clustered Index:

- A clustered index determines the physical order of data in a table.


- For this reason, a table can have only one clustered index.
2. Non Clustered Index:

- The data is stored in one place and the index is stored in another place.
- Since, the non-clustered index is stored separately from the actual data, a table can have more
than one non clustered index.
- The index will have pointers to the storage location of the data.

Difference between Clustered and Non-Clustered Index:


1. Only one clustered index per table, where as you can have more than one non clustered index
2. Clustered index is faster than a non-clustered index, because, the non-clustered index has to
refer back to the table, if the selected column is not present in the index.
3. Clustered index determines the storage order of rows in the table, and hence doesn't require
additional disk space, but whereas a Non Clustered index is stored separately from the table,
additional storage space is required.

Disadvantages of Indexes:

Additional Disk Space: Clustered Index does not, require any additional storage. Every Non-
Clustered index requires additional space as it is stored separately from the table. The amount
of space required will depend on the size of the table, and the number and types of columns
used in the index.

Insert Update and Delete statements can become slow: When DML (Data Manipulation
Language) statements (INSERT, UPDATE, DELETE) modifies data in a table, the data in all the
indexes also needs to be updated. Indexes can help, to search and locate the rows, that we want
to delete, but too many indexes to update can actually hurt the performance of data
modifications.

32. What is Covering Index?


- If all the columns that we have requested in the SELECT clause of query, are present in the
index, then there is no need to look up in the table again. The requested columns data can
simply be returned from the index.

A clustered index, always covers a query, since it contains all of the data in a table. A composite
index is an index on two or more columns. Both clustered and non clustered indexes can be
composite indexes. To a certain extent, a composite index, can cover a query.
33. Scenario : Interviewer may give you a table and a query and ask you for on which column
should I create a Clustered Index and Why?
Let’s say there is a Employee table with Id Column as a Primary Key :

We have below query in SP which is very slow :


SELECT Id, Name, Salary, Gender from Employee Where Salary BETWEEN 2500 AND 50000
- This query has more focus on Salary column so we should have something over Salary column
which will help this query to execute faster.
- Firstly we can go ahead and create a non clustered index on Salary Column and we will check
the results. If this works then we are good but if this fails then we have to go with creating
Clustered Index on Salary by removing Clustered Index from Primary Key Id Column. Which will
definitely helps this query to run faster.

34.
What are Views? Indexed View? Advantages of Views?
-A view is nothing more than a saved SQL query.
-A view can also be considered as a virtual table.
-When we try to retrieve data from the view, the data is actually retrieved from the underlying
base tables. So, a view is just a virtual table it does not store any data, by default.
- However, when we create an index, on a view, the view gets materialized. This means, the view
is now, capable of storing data. In SQL server, we call them Indexed views.

Advantages of using views:

1. Views can be used to reduce the complexity of the database schema, for non IT users. For
example the view can hides the complexity of joins. Non-IT users, finds it easy to query the
view, rather than writing complex joins.
2. Views can provide row and column level security.

Row Level Security:


For example, I want an end user, to have access only to IT Department employees. If I grant him
access to the underlying tblEmployees and tblDepartments tables, he will be able to see, every
department employees. To achieve this, I can create a view, which returns only IT Department
employees, and grant the user access to the view and not to the underlying table.

Column Level Security:


Salary is confidential information and I want to prevent access to that column. To achieve this,
we can create a view, which excludes the Salary column, and then grant the end user access to
these views, rather than the base tables.
35. Can we update underlying base tables through View? [Tricky question] Depending on your
answer he can ask you Single/Multiple base tables?
- Yes. We can update the base tables through a view if there is single underlying base table.
- For a view based on multiple base tables we can use instead of trigger to correctly update the
base table values.

36. What are Triggers? Different types of Triggers?


- A trigger is a special type of stored procedure that automatically fires against some action
occurs in the database server.
- There are different types of triggers :
1. DML Triggers which are again divided into Instead Of Triggers and After Triggers
2. DDL Triggers
3. Logon Triggers.

DML Triggers :
- DML triggers are fired whenever data is modified using INSERT, UPDATE and DELETE events.
- DML triggers can be again classified into 2 types.

1. After or For triggers


- After trigger will be fired and executed after performing the Insert, Update and Delete
actions successfully.
2. Instead of triggers
- Instead Of trigger allow you to skip an Insert, Update and Delete actions on table and
execute other statements defined in the trigger instead.

DDL Triggers :
- DDL triggers fire in response to DDL events i.e. for CREATE, ALTER and DROP (Table, Function,
Index, Stored Procedure etc...).

Logon Triggers :
- As the name implies Logon triggers fire in response to a LOGON event.
- Logon triggers fire after the authentication phase of logging in finishes, but before the user
session is actually established.
Logon triggers can be used for
1. Tracking login activity
2. Restricting logins to SQL Server
3. Limiting the number of session for a specific user
37. What are different magical/special tables available in Triggers?
- There are 2 magical tables available while working with triggers:
1. INSERTED Table
- When you add a new row in a table then a copy of the row will be made into inserted
table which only a trigger can access.
2. DELETED Table
- When you delete a row from a table then a copy of the row will be made into deleted
table which only a trigger can access.

38. Can I save activities of user on my database? If yes then how?


- Yes. We can save all activities of a user on a specific database or on all databases from a server.
- We can use DDL Trigger on a database or on a server to log the activities of user in a particular
table
[Note : Interviewer may ask you to write a syntax for creating database or server scoped DDL Trigger.]

39. Can we limit connections for a particular user? If yes then how?
- Yes. We can limit the connections for a particular user.
- We can use Logon Triggers to achieve this.
[Note : Interviewer may extend his question by asking how to create that trigger. Remember the syntax of creating
LOGON Trigger.]

40. How Error handling done in SQL? Have you done error handling in your project?
- We use Try Catch block just like C# language to catch and handle the exceptions in SQL.
- We cannot use try catch blocks in functions.
- If we have to through error to calling application then we use RAISERROR function in catch
block.
- Also we specify ROLLBACK command in catch block when we are dealing with transactions.
- RAISEERROR Function is use to throw exception directly to the calling application.
Syntax of RAISEERROR Function is
RAISERROR('Error Message', ErrorSeverity, ErrorState)
- Severity and State are integers. In most cases, when you are returning custom errors, the
severity level is 16, which indicates general errors that can be corrected by the user.
- ErrorState is also an integer between 1 and 255. RAISERROR only generates errors with state
from 1 through 127.

41. What are transactions in SQL? What all commands used in Transaction?
- A transaction is a group of commands that change the data stored in a database.
- A transaction is treated as a single unit.
- A transaction ensures that, either all of the commands succeed, or none of them. If one of the
commands in the transaction fails, all of the commands fail, and any data that was modified in
the database is rolled back. In this way, transactions maintain the integrity of data in a database.
Transaction processing follows these steps:
1. Begin a transaction.
2. Process database commands.
3. Check for errors.
If errors occurred,
rollback the transaction,
else,
commit the transaction

- We use Commit command to commit the changes permanently to database and Rollback
command to rollback the changes on any error while working with transactions.

42. What are Row_Number(), Rank(), Dense_Rank() functions?

Row_Number function

- Returns the sequential number of a row starting at 1


- In Row_Number function ORDER BY clause is required.
- In Row_Number function PARTITION BY clause is optional.

Syntax : ROW_NUMBER() OVER (ORDER BY Col1, Col2)

Rank function

- Rank function skips rankings if there is a tie.


- In Rank function ORDER BY clause is required.
- In Rank function PARTITION BY clause is optional.

Syntax : Rank() OVER (ORDER BY Col1, Col2)

Dense_Rank function

- Dense_Rank function does not skips rankings if there is a tie.


- In Dense_Rank function ORDER BY clause is required.
- In Dense_Rank function PARTITION BY clause is optional.

Syntax : Dense_Rank() OVER (ORDER BY Col1, Col2)

43. What is Pivot and UnPivot in SQL?


- In short, PIVOT operator turns ROWS into COLUMNS whereas UNPIVOT turns COLUMNS into
ROWS.
44. How to delete duplicates rows from table.
with cte1
as
(
select Name,
ROW_NUMBER() over (partition by Name order by Name) As RowNumber
from sample1
)
delete from cte1
where RowNumber >1

45. How to find nth highest salary from employees table (explain different ways).

1st way using SubQuery :

SELECT TOP 1 SALARY


FROM (
SELECT DISTINCT TOP N SALARY
FROM EMPLOYEES
ORDER BY SALARY DESC
) RESULT
ORDER BY SALARY

2nd way using CTE :

WITH CTE AS
(
SELECT SALARY,
DENSE_RANK() OVER (ORDER BY SALARY DESC) AS DENSERANK
FROM EMPLOYEES
)
SELECT DISTINCT SALARY
FROM CTE
WHERE DENSERANK = N

[Please note we can use Row_Number() function over Dense_Rank() but if there are duplicates then Dense_Rank()
function gives correct output.]
46. What are ACID properties in SQL?
- All transaction must obey ACID properties.
- Atomicity : All statements in the transaction either completed successfully or none of them will
execute. But in any case not left half done.
- Consistency : A database is initially in a consistent state and it should remain consistent after
every transaction.
- Isolation : If the multiple transaction are running concurrently they should not be affected by
each other. Most database uses locking to maintain transaction isolation.
- Durability : Once a change in database is made it remain permanent in the case of any software
or hardware failure.

47. What is LOCK in SQL ?


- To avoid concurrency problem lock is used.
- Concurrency problem means multiple transactions can access table at same time.
- Lock can be applied on database, table, row.

48. What is SQL Profiler ?


- SQL server profiler is a tracing tool provided by Microsoft.
- It is used to trace activities and operations executed on a specific database or table or query.

49.
How to optimize SQL query?
- Select fields instead of using Select *
- Avoid Select Distinct use Group by to all fields in the query to create distinct results.
- Use Where instead of Having to define filters.
- Proper Indexes runs query faster for this create index on those columns which can be used in
where or group by clause.
- Avoid corelated sub queries as it search row by row.
- Use temporary table to handle bulk data.

50. What is Deadlock ?


- Deadlock is special concurrency problem in which two transaction block the progress of each
other.

51. How to avoid Deadlock ?


- Ensure the database design is properly normalized.
- Keep transaction as short as possible.
- Reduce the number of round trips between your application and sql server by using store
procedure.
52. Table Hints in SQL?
- Hint instructs the database engine on how to execute the query.
- Ex. a hint may tell the engine to use or not to use an Index.
- NoLock Hint : Allows SQL to read data by ignoring any locks this improves query performance.
- Rowlock Hint : That instructs database that it should keep locks on a row scope.

53. What are Cursors in SQL? Can you tell me what all steps are followed while using Cursors?
- If there is ever a need to process the rows, on a row-by-row basis, then cursors are your choice.
Cursors are very bad for performance, and should be avoided always. Most of the time, cursors
can be very easily replaced using joins.
There are different types of cursors in sql server as listed below.
1. Forward-Only
2. Static
3. Keyset
4. Dynamic

We use below steps while using the cursors :


- Declare the cursor
- Open statement
- Fetch the row from the result set into the variable
- @@Fetch_Status to check if result set still has rows
- Release the row set Deallocate the resources associated with the cursors.

[Note : If interviewer ask where did u use cursors in your project? Ans : I have never came across situation where I can
implement cursors in my project. Again they are bad over performance.

Advanced Questions :

54. Isolation Level in SQL and its Types


55. Query Execution Plan
WEB API Question Answer
1. What is Web API ?
 Web API is framework which used to develop http restful services.
 Web API is service where we can write code once and consume it in any application.
 In our Web API project, we wrote business logic and consume it in MVC application.

2. What is differences between Web API and WCF ?


 Both are used create restful services but Web API is lightweight as compared to WCF.
 Because in WCF we need lot of config settings and complicated for developing restful
services.

3. Web API is replacement for WCF ?


 No, Web API is another way of develop non-SOAP based services i.e. plain XML or JSON
string.

4. What is Protocol ?
 Protocol means guidelines or rules to communicate over internet.
 Ex. http - Internet
tcp - Intranet (Communicate with LAN)
namedpipe – Used when same server
msmq - To maintain que

5. What is Serialization and Deserialization ?


 Serialization means converting dot net object into any message format.
 Deserialization means converting any message format into dot net object.

6. What is difference between SOAP and REST ?


 SOAP means Simple Object Access Protocol whereas REST means Representational
State Transfer.
 SOAP only uses XML data format whereas REST uses many data formats including Plain
Text, HTML, XML and JSON.

7. What are main return types supported in Web API?


 Void – It will return empty content.
 HttpResponseMessage – It will convert the response into an Http message.
 IHttpActionResult – It internally calls ExecuteAsync to create an HttpResponseMessage.

8. Web API supports which protocol?


 Web App supports HTTP protocol.

9. Which .NET framework supports Web API?


 NET 4.0 and above version supports web API.

10. Web API uses which of the following open-source library for JSON serialization?
 Web API uses Json.NET library for JSON serialization.
11. What is Web API Routing?
 Routing is pattern matching like in MVC.
 All routes are registered in Route Tables.
 Domain/Api/Controller

12. How can you handle errors in Web API?


 Several classes are available in Web API to handle errors like HttpError, Exception Filters,
HttpResponseException and Registering Exception Filters.

13. How can you pass multiple complex types in Web API?
 Two methods to pass the complex types in Web API – Using ArrayList and Newtonsoft
array.

14. How to test Web API ?


 We can use third party tools for testing Web API.
a) Fiddler
b) Postman
c) Swagger UI

15. What are the HTTP verbs/methods in Web API ?


 Get – Retrieves data
 Post – Insert new record
 Put – Update existing record
 Patch – Update records partially
 Delete – Delete records

16. What is difference between Web API and MVC ?


 Web API derives from System.Web.Http.ApiController whereas MVC derives from
System.Web.Mvc.Contoller
 In Web API method name must start with Http verbs otherwise apply http verbs
attribute whereas in MVC must apply appropriate Http verbs attribute.
 Web API specialized in returning data whereas MVC specialized in rendering view.

17. What are Request/Response data formats ?


 Accept – The accept header attribute specifies the format of response data.
 Content-Type – The content-type header attribute specifies the format of request data.

18. How to consume Web API in MVC ?


 To consume Web API in MVC we can use HttpClient class in MVC controller.
 HttpClient sends a request to the Web API and receives a response.
 Then we can convert response data to a model and then render it on a view.

19. How to authenticate user in Web API?


 There various ways to authenticate user in Web API.
 We used JWT token based authentication in Web API.
 JWT – means Jason Web Token
20. How does JWT authentication work ?
 The server generates a token that certifies the user identity and sends it to the client.
 The client will send the token back to the server for every subsequent request.
 So the server knows, the request comes from particular identity.

21. What is difference between synchronous and asynchronous request in AJAX ?


 In synchronous request, the working of a page and user interaction is blocked until a
response is received from the server.
 In an asynchronous request, the page continues to work normally without blocking the
user means that the user need not wait until the server replies. It is the most preferred
way of sending a request.

22. How to make AJAX synchronous ?


 In AJAX, there is flag called async and setting it false will make AJAX request
synchronous.

23. What is Open Authentication (OAuth) ?


 Open authentication is a type of token authentication it allows an end users account
information used by third party services such as Facebook without exposing users
username and password.
what are Lambda expressions?

A lambda expression is an anonymous function that can contain expressions and statements, and can be
used to create delegates or expression tree types.
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda
operator specifies the input parameters (if any) and the right side holds the expression or statement
block.

The => operator has th


Lambdas are used in method-based LINQ queries e same precedence as assignment (=) and is right-
associative.
as arguments to standard query operator methods such as Where and Where(IQueryable, String, array[]).

How do you assign a Lambda expression to a delegate?

delegate int del(int i);


del myDelegate = x => x * x;
int j = myDelegate(5); //j = 25

Can we write a lamba expression on the left side of the is or as operator?

Lambdas are not allowed on the left side of the is or as operator.

What is Expression Lambda?

A lambda expression with an expression on the right side is called an expression lambda. Expression
lambdas are used extensively in the construction of Expression Trees. An expression lambda returns the
result of the expression and takes the following basic form:

(input parameters) => expression

The parentheses are optional only if the lambda has one input parameter; otherwise they are required.
Two or more input parameters are separated by commas enclosed in parentheses:

(x, y) => x == y

Sometimes it is difficult or impossible for the compiler to infer the input types. When this occurs, you can
specify the types explicitly as shown in the following example:

(int x, string s) => s.Length > x

Specify zero input parameters with empty parentheses:

() => SomeMethod()

Note in the previous example that the body of an expression lambda can consist of a method call.
However, if you are creating expression trees that will be consumed in another domain, such as SQL
Server, you should not use method calls in lambda expressions. The methods will have no meaning
outside the context of the .NET common language runtime.

What is Statement Lambda?

A statement lambda resembles an expression lambda except that the statement(s) is enclosed in braces:
(input parameters) => {statement;}

The body of a statement lambda can consist of any number of statements; however, in practice there are
typically no more than two or three.

delegate void TestDelegate(string s);



TestDelegate myDel = n => { string s = n + " " + "World"; Console.WriteLine(s); };
myDel("Hello");

What is the difference between Statement Lambdas and Expression Lambdas ?

Expression lambdas are used extensively in the construction of Expression Trees.

Statement lambdas cannot be used to create expression trees.

What is Type Inference in Lambdas ?

When writing lambdas, you often do not have to specify a type for the input parameters because the
compiler can infer the type based on the lambda body, the underlying delegate type, and other factors as
described in the C# 3.0 Language Specification. For most of the standard query operators, the first input
is the type of the elements in the source sequence. So if you are querying an IEnumerable, then the input
variable is inferred to be a Customer object, which means you have access to its methods and properties:

customers.Where(c => c.City == "London");

Explain Rules of lambdas?


The lambda must contain the same number of parameters as the delegate type.
Each input parameter in the lambda must be implicitly convertible to its corresponding delegate
parameter.
The return value of the lambda (if any) must be implicitly convertible to the delegate's return type.

Does lambda expressions in themselves do have a type?

lambda expressions in themselves do not have a type because the common type system has no intrinsic
concept of "lambda expression." However, it is sometimes convenient to speak informally of the "type" of
a lambda expression. In these cases the type refers to the delegate type or Expression type to which the
lambda expression is converted.

Explain about Variable Scope in Lambda Expressions?

Lambdas can refer to outer variables that are in scope in the enclosing method or type in which the
lambda is defined. Variables that are captured in this manner are stored for use in the lambda expression
even if variables would otherwise go out of scope and be garbage collected. An outer variable must be
definitely assigned before it can be consumed in a lambda expression.

List out the rules apply to variable scope in lambda expressions?

A variable that is captured will not be garbage-collected until the delegate that references it goes out of
scope.
Variables introduced within a lambda expression are not visible in the outer method.
A lambda expression cannot directly capture a ref or out parameter from an enclosing method.
A return statement in a lambda expression does not cause the enclosing method to return.
A lambda expression cannot contain a goto statement, break statement, or continue statement whose
target is outside the body or in the body of a contained anonymous function.

What are Expression Trees?

Expression trees represent language-level code in the form of data. The data is stored in a tree-shaped
structure. Each node in the expression tree represents an expression, for example a method call or a
binary operation such as x <>
// Create an expression tree.

Expression<func> exprTree = num => num <>


// Decompose the expression tree.ParameterExpression param =
(ParameterExpression)exprTree.Parameters[0];BinaryExpression operation =
(BinaryExpression)exprTree.Body;ParameterExpression left =
(ParameterExpression)operation.Left;ConstantExpression right = (ConstantExpression)operation.Right;

are Expression Trees Immutable?

Expression trees are immutable. This means that if you want to modify an expression tree, you must
construct a new expression tree by copying the existing one and modifying it. You can use an expression
tree visitor to traverse the existing expression tree.

What is LINQ?

Language-Integrated Query (LINQ) is a set of features in Visual Studio 2008 that extends powerful query
capabilities to the language syntax of C# and Visual Basic. LINQ introduces standard, easily-learned
patterns for querying and updating data, and the technology can be extended to support potentially any
kind of data store.

Why LINQ is required?

Language-Integrated Query (LINQ) that bridges the gap between the world of objects and the world of
data.

Traditionally, queries against data are expressed as simple strings without type checking at compile time
or IntelliSense support. Furthermore, you have to learn a different query language for each type of data
source: SQL databases, XML documents, various Web services, and so on. LINQ makes a query a first-
class language construct in C# and Visual Basic. You write queries against strongly typed collections of
objects by using language keywords and familiar operators.
Ado.net
1. What is Ado.net ?
 Ado.net stands Microsoft ActiveX Data Objects.
 Ado.net is a set classes that can be used to interact with data sources like
database and XML.

2. What are the classes used in Ado.net ?


 SqlConnection
 SqlCommand
 SqlDataReader
 SqlDataAdapter
 Dataset

3. What are the steps to communicate database using Ado.net ?


 Connect to the Database
 Prepare an SQL Command
 Execute the Command
 Retrieve the results and display in the application

4. What is SqlCommand?
 SqlCommand class is used to prepare an Sql statement or Store Procedure that
we want to execute on Sql server database.
 There are three methods of SqlCommand class which are commonly used :
a) ExecuteScalar : Used when query returns single value.
b) ExecuteReader : Used when query returns more than one value.
c) ExecuteNonScalar : Used when we want to perform an Insert, Update or
Delete operations.

5. What is SqlDataReader?
 SqlDataReader reads data in the most efficient manner.
 SqlDataReader is connection oriented means it requires an active and open
connection to the data source while reading the data.

6. What is SqlDataAdapter and Dataset?


 SqlDataAdapter and Dataset provides us disconnected data access model.
 Dataset is the collection of datatables and datatable is a collection of datarows.
 Fill() method opens connection to the database, executes Sql command, fills
data in the dataset and closes the connection.

7. What is use SqlBulkCopy class ?


 SqlBulkCopy class is used to copy data from different data source into Sql server
database.
 Using SqlBulkCopy we can load XML data to Sql server.

8. What is Sql injection ?


 Sql injection is an attack where user can inject any script through textbox and
execute those unwanted scripts which harms our database.
 To prevent Sql injection we can use parametrized queries or store procedures.
use master
[THE ARJUN]

--To alter a database, once it's created


Alter database DatabaseName Modify Name = NewDatabaseName

--Alternatively, you can also use system stored procedure


Execute sp_renameDB 'OldDatabaseName','NewDatabaseName'

-- to rename table name


exec sp_rename 'TestTable' , 'NewTestTable'
--TO column name
EXECUTE sp_rename 'NewTestTable.Id' , 'NewId' , 'column'
----------------------------------------------------------

--Full Type
Backup database <Your database name> to disk = '<Backup file location + file name>'

--Differential Type
Backup database <Your database name> to
disk = '<Backup file location + file name>' with differential

--Log Type
Backup log <Your database name> to disk = '<Backup file location + file name>'

--Restoring a Database
Restore Database <Your database name> from disk = '<Backup file location + file name>
-------------------------------------------------
Drop Database Database_name
-----------------------------
Create Table tblGender
(ID int Not Null Primary Key ,
Gender nvarchar (50))
-------------
--to add column in existing table

alter table tblGender


add City varchar(20)

alter table tblGender


drop column city

Alter table tblPerson


add constraint tblPerson_GenderId_FK
FOREIGN KEY (GenderId) references tblGender(ID)
----
Alter table ForeignKeyTable
add constraint ForeignKeyTable_ForiegnKeyColumn_FK
FOREIGN KEY (ForiegnKeyColumn) references PrimaryKeyTable(PrimaryKeyColumn)
---------------
ALTER TABLE { TABLE_NAME }
ADD CONSTRAINT { CONSTRAINT_NAME }
DEFAULT { DEFAULT_VALUE } FOR { EXISTING_COLUMN_NAME }
-----
ALTER TABLE tblPerson
ADD CONSTRAINT DF_tblPerson_GenderId
DEFAULT 1 FOR GenderId
--------------
alter table tblperson
add constraint Ck_tblperson_age
check(age > 0 AND age<=100 )
--------------

alter table tblperson


add constraint UQ_tblperson_mobile
unique (mobile)
-------------

alter table tblperson


add constraint Pk_tblperson_id
primary key (id)
--but id colun must not allow null,set it graphically.if there is duplicate records then delete that
records.
-------------
drop constraint {constraint_name}
---------
EXECUTE SP_HELPCONSTRAINT tblEmployee
-------------
Insert into tblPerson(ID,Name,Email,GenderId) values (6, 'Dan' , '[email protected]' , NULL )

Insert into tblPerson(ID,Name,Email) values (5, 'Sam' , '[email protected]' )


----------
ALTER TABLE { TABLE_NAME }
DROP CONSTRAINT { CONSTRAINT_NAME }
----------
--Cascading referential integrity constraint

create table tblGender


(
Id int primary key ,
Name varchar ( 50 )
)
create table tblPerson
(
Id int primary key ,
Name varchar ( 50 ),
GenderId int
)
Alter table tblPerson
Add constraint FK_tblPerson_GenderId
foreign key references tblGender ( Id ) on delete no action

on delete no action
on delete cascade
on delete set null
on delete set default
--------------
--Identity column

Create Table tblPerson


(
PersonId int Identity (1,1) Primary Key ,
Name nvarchar (20)
)
Insert into tblPerson values ( 'Sam' )

To explicitly supply a value for identity column, First turn on identity insert
SET Identity_Insert tblPerson ON

after that
SET Identity_Insert tblPerson OFF

This command will reset PersonId identity column.


DBCC CHECKIDENT(tblPerson, RESEED, 0) --database check constraint
---------------
--How to get the last generated identity column value in SQL Server
Select SCOPE_IDENTITY()
Select @@IDENTITY
Select IDENT_CURRENT('tblPerson')
--------------
--to make column data negative signed

select Id from student


where sign(Id)=-1
SELECT MIN ( salary ) AS Minimum_Salary
FROM tblEmployee

SELECT City , MIN ( salary ) FROM tblEmployee


GROUP BY City

Select City, Gender, SUM (Salary) as TotalSalary


from tblEmployee
group by City, Gender

------------
--JOINS

inner join
left outer join or left join
right uoter join or right join
full outer join or full join
cross join

self join
-joining with itself with some alias.
inner join /inner self join
left join /left outer self join
right join / irght outer self join
full join /full outer join
cross join
-----------------------
==Different ways to replace NULL in sql server
--Replacing NULL value using ISNULL() function:

SELECT E.Name as Employee, ISNULL (M.Name, 'No Manager' ) as Manager


FROM tblEmployee E
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID

--Replacing NULL value using CASE Statement:

SELECT E.Name as Employee,


(CASE
WHEN M.Name IS NULL THEN 'No Manager'
ELSE M.Name
END) as Manager
FROM tblEmployee E
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID
--Replacing NULL value using COALESCE() function: COALESCE() function, returns the first
NON NULL value.

SELECT E.Name as Employee, COALESCE (M.Name, 'No Manager' ) as Manager


FROM tblEmployee E
LEFT JOIN tblEmployee M
ON E.ManagerID = M.EmployeeID

SELECT Id, COALESCE (FirstName, MiddleName, LastName) AS Name


FROM tblEmployee

-----------------
==Union and union all in sql server

Select Id, Name, Email from tblIndiaCustomers


UNION ALL
Select Id, Name, Email from tblUKCustomers

-- union all,union,intersect,except

--to sort results using order by clause

Select Id, Name, Email from tblIndiaCustomers


UNION ALL
Select Id, Name, Email from tblUKCustomers
UNION ALL
Select Id, Name, Email from tblUSCustomers
Order by Name

----------------
==Subqueries
--subquery used in where clause

Select [Id], [Name], [Description]


from tblProducts
where Id not in ( Select Distinct ProductId from tblProductSales)

--subquery used in select statement


Select [Name],
( Select SUM (QuantitySold) from tblProductSales where ProductId =
tblProducts.Id) as TotalQuantity
from tblProducts
order by Name
---------------------
==Stored Procedure
--Creating a simple stored procedure without any parameters :

Create Procedure spGetEmployees


as
Begin
Select Name, Gender from tblEmployee
End

to execute SP
1. spGetEmployees
2. EXEC spGetEmployees
3. Execute spGetEmployees

--Creating a stored procedure with input parameters: This SP, accepts GENDER and
DEPARTMENTID parameters. Parameters and variables have an @ prefix in their name.

Create Procedure spGetEmployeesByGenderAndDepartment


@Gender varchar (50),
@DepartmentId int
with encryption
as
Begin
Select Name, Gender from tblEmployee Where Gender = @Gender and DepartmentId
=@DepartmentId
End

EXECUTE spGetEmployeesByGenderAndDepartment @DepartmentId=1, @Gender = 'Male'

Use system sp to view the text of SP


exec sp_helptext 'SPName'

this is used for sp,tables,triggers,views.


exec sp_help {sp name}

sp_depends {SP_Name}

DROP PROC 'SPName' or DROP PROCEDURE 'SPName

--Stored procedures with output parameters

Create Procedure spGetEmployeeCountByGender


@Gender nvarchar (20),
@EmployeeCount int Output
as
Begin
Select @EmployeeCount = COUNT (Id)
from tblEmployee
where Gender = @Gender
End

Declare @EmployeeTotal int


Execute spGetEmployeeCountByGender 'Female' , @EmployeeTotal output
Print @EmployeeTotal

--Optional parameters in sql server stored procedures


Create Proc spSearchEmployees
@Name nvarchar (50) = NULL ,
@Email nvarchar (50) = NULL ,
@Age int = NULL ,
@Gender nvarchar (50) = NULL
as
Begin
Select * from tblEmployee where
(Name = @Name OR @Name IS NULL ) AND
(Email = @Email OR @Email IS NULL ) AND
(Age = @Age OR @Age IS NULL ) AND
(Gender = @Gender OR @Gender IS NULL )
End
Testing the stored procedure
1. Execute spSearchEmployees -- This command will return all the rows
2. Execute spSearchEmployees @Gender = 'Male' -- Retruns only Male employees
3. Execute spSearchEmployees @Gender = 'Male' , @Age = 29 -- Retruns Male employees
whose age is 29

----------------------
--------------------------------------
==Built in string functions in SQL

Select ASCII ( 'A' )


CHAR (Integer_Expression)

--while loop
Declare @Number int
Set @Number = 65
While (@Number <= 95)
Begin
Print char(@Number)
Set @Number = @Number + 1
End

Select LTRIM ( ' Hello' )


Select RTRIM ( 'Hello ' )

Select LTRIM ( RTRIM (' Hello '))

Select LOWER (Character_Expression)

Select UPPER (Character_Expression)

Select REVERSE (Character_Expression)

Select LEN (String_Expression)

Select LEFT ( 'ABCDE' , 3)

Select RIGHT ( 'ABCDE' , 3)

Select CHARINDEX ( '@' , '[email protected]' ,1)


--(what to search,in what,start pt)
Select SUBSTRING ( '[email protected]' ,6, 7)
--(in what,start pt,length)

Select SUBSTRING (Email, CHARINDEX ( '@' , Email) + 1,LEN (Email) - CHARINDEX (


'@' , Email)) as EmailDomain,
COUNT (Email) as Total
from tblEmployee1
Group By SUBSTRING (Email, CHARINDEX ( '@' , Email) + 1,LEN (Email) - CHARINDEX
( '@' , Email))

SELECT REPLICATE ( 'SQL' , 3)

Select FirstName, LastName, SUBSTRING (Email, 1, 2) + REPLICATE ( '*' ,5) +


SUBSTRING (Email, CHARINDEX ( '@' ,Email), LEN (Email) - CHARINDEX ( '@'
,Email)+1) as Email
from tblEmployee

Select FirstName + SPACE (5) + LastName as FullName


From tblEmployee

Select Email, PATINDEX ( '%@aaa.com' ,Email) as FirstOccurence


from tblEmployee

Select Email, REPLACE (Email, '.com' , '.net' ) as ConvertedEmail


from tblEmployee

Select Email, STUFF (Email, 2, 3, '*****' ) as StuffedEmail


From tblEmployee
-----------------------------
==DateTime functions in SQL Server

DATATYPES
DATE,TIME,SMALLDATETIME,DATETIME,DATETIME2,DATETIMEOFFSET

Select ISDATE ( Getdate ()) -- returns 1


Select ISDATE ( ‘sql’ ) -- returns 0
Select DAY ( '01/31/2012' ) -- Returns 31
Select Month ( '01/31/2012' ) -- Returns 1
Select Year ( '01/31/2012' ) -- Returns 2012

----------------
Select DATENAME ( Day , '2012-09-30 12:43:46.837' ) -- Returns 30
Select DATENAME ( WEEKDAY , '2012-09-30 12:43:46.837' ) -- Returns Sunday
Select DATENAME ( MONTH , '2012-09-30 12:43:46.837' ) -- Returns September
-----------------
Select DATEPART ( weekday , '2012-08-30 19:45:31.793' ) -- returns 5
Select DATENAME ( weekday , '2012-08-30 19:45:31.793' ) -- returns Thursday
-----------------
DATEADD (datepart, NumberToAdd, date)
Select DateAdd ( DAY , 20, '2012-08-30 19:45:31.793' )
-- Returns 2012-09-19 19:45:31.793
------------------
DATEDIFF (datepart, startdate, enddate)
Select DATEDIFF ( MONTH , '11/30/2005','01/31/2006' ) -- returns 2
Select DATEDIFF ( DAY , '11/30/2005','01/31/2006' ) -- returns 62

-------------------
Syntax of CAST and CONVERT functions from MSDN:
CAST ( expression AS data_type [ ( length ) ] )
CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

CAST (DateofBirth as nvarchar )


select Convert ( nvarchar , DateOfBirth, 103)

SELECT CONVERT ( VARCHAR (10), GETDATE (),104)


SELECT CAST ( GETDATE () as DATE )
SELECT CONVERT ( DATE , GETDATE ())
select convert (varchar(50),getdate())

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

==Mathematical functions in sql server


Select ABS (-101.5) -- returns 101.5, without the - sign.

Select CEILING (15.2) -- Returns 16


Select CEILING (-15.2) -- Returns -15

Select FLOOR (15.2) -- Returns 15


Select FLOOR (-15.2) -- Returns -16

Select POWER (2,3) -- Returns 8

Select RAND (1) -- Always returns the same value

select RAND()---always return different value between 0 to 1

Select FLOOR ( RAND () * 100)

---------------
Declare @Counter int
Set @Counter = 1
While (@Counter <= 10)
Begin
Print FLOOR ( RAND () * 100)
Set @Counter = @Counter + 1
End
---------------
Select SQUARE (9) -- Returns 81

Select SQRT (81) -- Returns 9

Select ROUND (850.556, 2) -- Returns 850.560


Select ROUND (850.556, 2, 1) -- Returns 850.550
Select ROUND (850.556, 1) -- Returns 850.600
Select ROUND (850.556, 1, 1) -- Returns 850.500
Select ROUND (850.556, -2) -- 900.000
Select ROUND (850.556, -1) -- 850.000

SELECT EOMONTH ( '11/20/2015' ) AS LastDay --2015-11-30


SELECT EOMONTH ( '3/20/2016' , 2) AS LastDay --2016-05-31
SELECT EOMONTH ( '3/20/2016' , -1) AS LastDay --2016-02-29 --february
-----------------------------------

==DATEFROMPARTS function in SQL Server

Syntax : DATEFROMPARTS ( year , month , day )

SELECT DATEFROMPARTS ( 2015, 10, 25) AS [Date]


-----------
Syntax : TIMEFROMPARTS ( hour, minute, seconds, fractions, precision )
SELECT TIMEFROMPARTS ( 23, 59, 59, 0, 0 )

select TIMEFROMPARTS (5,15,45,1231231,7 )

select TIMEFROMPARTS (5,15,45,12312,7 )


-----------
Syntax : SMALLDATETIMEFROMPARTS ( year , month , day , hour , minute )

select SMALLDATETIMEFROMPARTS (2015,11,24,5,15)


-----------
syntax : DATETIMEFROMPARTS ( year , month , day , hour , minute , seconds , milliseconds )

select DATETIMEFROMPARTS(2015,11,24,5,15,45,123)
--The datetimefromparts function requires 7 argument(s)
------------
Syntax : DATETIME2FROMPARTS ( year, month, day, hour, minute, seconds, fractions,
precision )

select DATETIME2FROMPARTS (2015,11,24,5,15,45,123,7)


--just precision part increased,The datetime2fromparts function requires 8 argument(s)
------------

Syntax :
DATETIMEOFFSETFROMPARTS ( year, month, day, hour, minute, seconds, fractions,
hour_offset, minute_offset, precision )

select DATETIMEOFFSETFROMPARTS (2015,11,24,5,15,45,123,5,30,3)


--fractions=<precision then there is no error

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

==Scalar User Defined Functions in sql server

--To create a function, we use the following syntax:

CREATE FUNCTION Function_Name(@Parameter1 DataType, @Parameter2


DataType,..@Parametern Datatype)
RETURNS Return_Datatype
AS
BEGIN
Function Body
Return Return_Datatype
END
---------------
--scalar UDF
--RETURNS single scalar value

--simple scalar fn means without parameter


create function fn_studentCount()
returns int
with schemabinding
as
begin
declare @c int
select @c=count(*) from student
return @c
end
select dbo.fn_studentCount()

--parameterized scalar fn

create function fn_studentCount(@gender varchar(10))


returns int
with schemabinding --it prevents to drop table on which table based,mandatory to use dbo at
table name
as
begin
declare @c int
select @c=count(*) from dbo.student where gender=@gender
return @c
end
select dbo.fn_studdentCount('male')

create function fn_studentCount(@gender varchar(10))


returns int
with Encryption---IT Encrypts the text of fn
as
begin
declare @c int
select @c=count(*) from student where gender=@gender
return @c
end
select dbo.fn_studdentCount('male')

ALTER FUNCTION FuncationName

DROP FUNCTION FuncationName

-----------------
--Inline table valued functions
--Syntax for creating an inline table valued function
CREATE FUNCTION Function_Name(@Param1 DataType, @Param2 DataType..., @ParamN
DataType)
RETURNS TABLE
AS
RETURN (Select_Statement)

CREATE FUNCTION fn_EmployeesByGender(@Gender nvarchar (10))


RETURNS TABLE
AS
RETURN
( Select Id, Name, DateOfBirth, Gender, DepartmentId
from tblEmployees
where Gender = @Gender)

Select * from fn_EmployeesByGender( 'Male' )


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

--Multi-statement Table Valued function(MSTVF):

Create Function fn_MSTVF_GetEmployees()


Returns @Table Table (Id int , Name nvarchar (20), DOB Date )
as
Begin
Insert into @Table

Select Id, Name, Cast (DateOfBirth as Date )


From tblEmployees

Return
End

Select * from fn_MSTVF_GetEmployees()


-----------------------------------------
==Temporary tables in SQL Server
--local temp table

Create Procedure spCreateLocalTempTable


as
Begin

Create Table #PersonDetails(Id int , Name nvarchar (20))

Insert into #PersonDetails Values (1, 'Mike' )


Insert into #PersonDetails Values (2, 'John' )
Insert into #PersonDetails Values (3, 'Todd' )

Select * from #PersonDetails


End
exec spCreateLocalTempTable --it gives table
Select * from #PersonDetails--it cannnot give table,bcoz it is outside of sp
----------------------
--global temp table
Create Table ##PersonDetails
(Id int ,
Name nvarchar (20))

Insert into ##PersonDetails Values (1, 'Mike' )


Insert into ##PersonDetails Values (2, 'John' )
Insert into ##PersonDetails Values (3, 'Todd' )

Select * from ##PersonDetails


--------------------------------
==Table Variables

declare @table table


(
id int,
name varchar(50)
)
select * from @table

insert into @table values(1,'arjun')


select * from @table

--If speed is an issue Table variables can be faster, but if there are a lot of records, or there is a
need to search the
--temporary table based on a clustered index, then a Temporary Table would be better. If you
have less
--than 100 rows generally use a table variable. Otherwise use a temporary table. This is because
SQL
--Server won't create statistics on table variables.
-------------------------------
==Select into in sql server

--1. Copy all rows and columns from an existing table into a new table. This is extremely useful
--when you want to make a backup copy of the existing table.

SELECT * INTO EmployeesBackup FROM Employees

--2. Copy all rows and columns from an existing table into a new table in an external database.
SELECT * INTO HRDB.dbo.EmployeesBackup FROM Employees

--3. Copy only selected columns into a new table

SELECT Id, Name, Gender INTO EmployeesBackup FROM Employees

--4. Copy only selected rows into a new table

SELECT * INTO EmployeesBackup FROM Employees WHERE DeptId = 1

--5. Copy columns from 2 or more table into a new table

SELECT * INTO EmployeesBackup


FROM Employees
INNER JOIN Departments
ON Employees.DeptId = Departments.DepartmentId

--6. Create a new table whose columns and datatypes match with an existing table.

SELECT * INTO EmployeesBackup FROM Employees WHERE 1 <> 1

--7. Copy all rows and columns from an existing table into a new table on a different SQL Server
--instance. For this, create a linked server and use the 4 part naming convention

SELECT * INTO TargetTable


FROM [SourceServer].[SourceDB].[dbo].[SourceTable]
--------------------------------
==INDEXES in sql server

--to view text


Execute sp_ helpindex tblEmployee

--To delete or drop the index: When dropping an index, specify the table name as well
Drop Index tblEmployee.IX_tblEmployee_Salary

--unique clustered index


Create unique Clustered Index IX_tblEmployee_Name
ON tblEmployee(Name)

--non unique clustered index/clustered index


Create Clustered Index IX_tblEmployee_Name
ON tblEmployee(Name)

--non unique nonclustered index/index


Create Index IX_tblEmployee_Name
ON tblEmployee(Name)

--unique NonClustered Index /unique


Create unique Index IX_tblEmployee_Name
ON tblEmployee(Name)

----------------------------------
==Views in sql server

Create View vW_ITDepartment_Employees


as
Select Id, Name, Salary, Gender, DeptName
from tblEmployee
join tblDepartment
on tblEmployee.DepartmentId = tblDepartment.DeptId
where tblDepartment.DeptName = 'IT'

select * from vW_ITDepartment_Employees

--View that returns summarized data,aggrgated data , Total number of employees by


Department.

Create View vWEmployeesCountByDepartment


with schemabinding
as
Select DeptName, COUNT(Id) as TotalEmployees
from tblEmployee
join tblDepartment
on tblEmployee.DepartmentId = tblDepartment.DeptId
Group By DeptName

--To look at view definition -


sp_helptext vWName

--To modify a view -


ALTER VIEW statement

--To Drop a view -


DROP VIEW vWName
---------------------------------------
== DML Triggers
In SQL server there are 3 types of triggers
1. DML triggers
2. DDL triggers
3. Logon trigger
CREATE TRIGGER tr_tblEMployee_ForInsert
ON tblEmployee
FOR INSERT ----same for delete and update
AS
BEGIN
Declare @Id int
Select @Id = Id from inserted ----- inserted and deleted are two magical tables
insert into tblEmployeeAudit
values ( 'New employee with Id = ' + Cast (@Id as nvarchar (5)) + ' is added at
' + cast ( Getdate () as nvarchar (20)))
END
-------------------
--Syntax for creating DDL trigger

CREATE TRIGGER [Trigger_Name]


ON [Scope (Server|Database)]
FOR [EventType1, EventType2, EventType3, ...],
AS
BEGIN
-- Trigger Body
END

--DDL triggers scope : DDL triggers can be created in a specific database or at the server level.

--The following trigger will fire in response to CREATE_TABLE DDL event.

CREATE TRIGGER trMyFirstTrigger


ON Database
FOR CREATE_TABLE ---create_table,alter_table,drop_table u can also add all statements
AS
BEGIN
Print 'New table created'
END

ALTER TRIGGER trMyFirstTrigger


ON Database
FOR CREATE_TABLE, ALTER_TABLE, DROP_TABLE
AS
BEGIN
Print 'A table has just been created, modified or deleted'
END
--Now if you create, alter or drop a table, the trigger will fire automatically and you will get the
message - A table has just been created, modified or deleted.

ALTER TRIGGER trMyFirstTrigger


ON Database
FOR CREATE_TABLE, ALTER_TABLE, DROP_TABLE
AS
BEGIN
Rollback
Print 'You cannot create, alter or drop a table'
END

DISABLE TRIGGER trMyFirstTrigger ON DATABASE

ENABLE TRIGGER trMyFirstTrigger ON DATABASE

DROP TRIGGER trMyFirstTrigger ON DATABASE

CREATE TRIGGER trRenameTable


ON DATABASE
FOR RENAME
AS
BEGIN
Print 'You just renamed something'
END

sp_rename 'TestTable' , 'NewTestTable'

sp_rename 'NewTestTable.Id' , 'NewId' , 'column'

--THIS TRIGGER PREVENTS FROM CREATE,DROP,ALTER TABLE


CREATE TRIGGER tr_DatabaseScopeTrigger
ON DATABASE --IF U REPLACE DATABASE BY ALL SERVER,THEN IT WILL
APPLIED ALL DATABASES
FOR CREATE_TABLE, ALTER_TABLE, DROP_TABLE
AS
BEGIN
ROLLBACK
Print 'You cannot create, alter or drop a table in the current database'
END

--Logon trigger example : The following trigger limits the maximum number of open
connections for a user to 3.

CREATE TRIGGER tr_LogonAuditTriggers


ON ALL SERVER
FOR LOGON
AS
BEGIN
DECLARE @LoginName NVARCHAR (100)
Set @LoginName = ORIGINAL_LOGIN ()
IF ( SELECT COUNT (*) FROM sys . dm_exec_sessions
WHERE is_user_process = 1
AND original_login_name = @LoginName) > 3
BEGIN
Print 'Fourth connection of ' + @LoginName + ' blocked'
ROLLBACK
END
END
----------------------------------------------------------
-- Gets the list of all objects
Select * from SYSOBJECTS where XTYPE= 'U'

-- Gets the list of tables only


Select * from SYS.TABLES
Select * from SYS.views

Select name from SYS.TABLES where name='teaassign'

-- Gets the list of tables and views


Select * from INFORMATION_SCHEMA.TABLES

--To get the list of different object types (XTYPE) in a database


Select Distinct XTYPE from SYSOBJECTS
-----------------------------
==Writing re-runnable sql server scripts

If not exists ( select * from information_schema.tables where table_name = 'tblEmployee' )


Begin
Create table tblEmployee
(
ID int identity primary key ,
Name nvarchar (100),
Gender nvarchar (10),
DateOfBirth DateTime
)
Print 'Table tblEmployee successfully created'
End
Else
Begin
drop table tblemployee
Create table tblEmployee
(
ID int identity primary key ,
Name nvarchar (100),
Gender nvarchar (10),
DateOfBirth DateTime
)
End
------------
--Sql server built-in function OBJECT_ID (), can also be used to check for the existence of the
table
IF OBJECT_ID ( 'tblEmployee' ) IS NULL
Begin
-- Create Table Script
Print 'Table tblEmployee created'
End
Else
Begin
Print 'Table tblEmployee already exists'
End
------------
--To make this script re-runnable, check for the column existence
if not exists ( Select * from INFORMATION_SCHEMA.COLUMNS where
COLUMN_NAME= 'EmailAddress' and TABLE_NAME = 'tblEmployee' and
TABLE_SCHEMA= 'dbo' )
Begin
ALTER TABLE tblEmployee
ADD EmailAddress nvarchar (50)
End
Else
BEgin
Print 'Column EmailAddress already exists'
End
-----------
If col_length ( 'tblEmployee' , 'EmailAddress' ) is not null
Begin
Print 'Column already exists'
End
Else
Begin
Print 'Column does not exist'
End
--------------------------------------
==Derived table and CTE in sql server

--Using Derived Tables


--Derived tables are available only in the context of the current query.

Select DeptName, TotalEmployees


from
(
Select DeptName, DepartmentId, COUNT (*) as TotalEmployees
from tblEmployee
join tblDepartment
on tblEmployee.DepartmentId = tblDepartment.DeptId
group by DeptName, DepartmentId
)
as EmployeeCount
where TotalEmployees >= 2
-------------------------------------
--COMMON TABLE EXPRESSION
Using CTE
With EmployeeCount(DeptName, DepartmentId, TotalEmployees)
as
(
Select DeptName, DepartmentId, COUNT (*) as TotalEmployees
from tblEmployee
join tblDepartment
on tblEmployee.DepartmentId = tblDepartment.DeptId
group by DeptName, DepartmentId
)
Select DeptName, TotalEmployees
from EmployeeCount
where TotalEmployees >= 2

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

With EmployeeCount(DepartmentId, TotalEmployees)


as
(
Select DepartmentId, COUNT (*) as TotalEmployees
from tblEmployee
group by DepartmentId
)
Select DeptName, TotalEmployees
from tblDepartment
join EmployeeCount
on tblDepartment.DeptId = EmployeeCount.DepartmentId
order by TotalEmployees
---------
--update based on single table
With Employees_Name_Gender
as
(
Select Id, Name, Gender from tblEmployee
)
Update Employees_Name_Gender Set Gender = 'Female' where Id = 1
------------------
==Recursive CTE
--A CTE that references itself is called as recursive CTE . Recursive CTE's can be of great help
when displaying hierarchical data.

with cte
as
(
select id,name,managerid,1 as level from employee where managerid is null
union all
select e.id,e.name,e.managerId,cte.level+1
from employee e join cte
on e.managerId=cte.id
where e.managerid is not null
)
select * from cte
------------------------------
==Cursors in sql server

declare @name varchar(10)

declare employeeCursor cursor for


select name from employee

open employeeCursor

fetch next from employee into @name

while (@@fetch_status=0)
begin
if @name ='mhesh'
begin
update tblemployee set salary=10000 where name=@name
end
if @name='dipak'
begin
update tblemployee set salary=10000 where name=@name
end
fetch next from employee into @name
end

close employeeCursor

deallocate employeeCursor
--------------------------------------------------
==Transaction
Create Procedure spUpdateAddress
as
Begin
Begin Try
Begin Transaction
Update tblMailingAddress set City = 'LONDON'
where AddressId = 1 and EmployeeNumber = 101
Update tblPhysicalAddress set City = 'LONDON'
where AddressId = 1 and EmployeeNumber = 101
Commit Transaction
End Try
Begin Catch
Rollback Transaction
End Catch
End
-------------
==Transaction Acid Tests
A - Atomic
C - Consistent
I - Isolated
D - Durable
-------------------------------
ROW_NUMBER () OVER ( ORDER BY Col1 , Col2 )
ROW_NUMBER () OVER ( partition by col1,col2 ORDER BY Col1 , Col2 )

SELECT Name , Gender , Salary ,


ROW_NUMBER () OVER ( ORDER BY Gender ) AS RowNumber FROM Employees

SELECT Name , Gender , Salary ,


ROW_NUMBER () OVER ( PARTITION BY Gender ORDER BY Gender ) AS RowNumber
FROM Employees

RANK () returns - 1, 1, 3, 4, 5
DENSE_RANK returns - 1, 1, 2, 3, 4
Syntax :
RANK () OVER ( ORDER BY Col1, Col2, ...)
DENSE_RANK () OVER ( ORDER BY Col1, Col2, ...)

NTILE (Number_of_Groups) OVER ( ORDER BY Col1, Col2, ...)

SELECT Name, Gender, Salary,


NTILE (3) OVER ( ORDER BY Salary) AS [Ntile]
FROM Employees

------------------------------------------------
==Pivot operator in sql server

--Query using PIVOT operator:

Select SalesAgent, India, US, UK


from tblProductSales
Pivot
(
Sum (SalesAmount) for SalesCountry in ([India],[US],[UK])
) as PivotTable

---query using unpivot:

SELECT SalesAgent , Country , SalesAmount


FROM tblProductSales
UNPIVOT
(
SalesAmount
FOR Country IN ( India , US , UK )
) AS UnpivotExample

-------------------------------
--select top n th salary
select top 1 salary from student where salary in(
select top 2 salary from student
order by salary desc)
ASP.NET Question-Answer
1. What is ASP.NET ?
 ASP.NET is Microsoft’s framework to build Web applications.
 In ASP.NET we create aspx pages.
 In ASP.NET user request for physical file i.e. aspx page

2. From which base class all web forms are inherited ?


 Page class

3. What is Event ? Explain its types ?


 Events get automatically fires against some action.
Types :

1) Application Level Events :


 Application level events fires when application starts.
 These events fire once.
 Application level events located in global.asax.cs file.
 Global class inherits HttpApplication class.
 Application level events are as follows :
a) Application_Start
b) Session_Start
c) Application_BeginRequest
d) Application_EndRequest
e) Session_End
f) Application_End

2) Page Level Events :


 Page level events are Page specific.
 Page level events are as follows :
a) Page_PreInit
b) Page_Init
c) Page__Load
d) Page_PreRender
e) Page_PreRenderComplete

3) Control Level Events :


 Control level events are Control specific.
 Control level events are as follows :
a) Postback event
b) Cached event
4. What are the State Management Techniques ?
 Http is stateless protocol means all information that associated with the page along
with the controls on the page would be lost with each roundtrip from browser.
 To overcome this type of problems, we use state management techniques which
maintains and stores the information of any user till the end of the user session.
 There two types of state management techniques :
1) Client-Side State Management Techniques
 In Client based option, information get stored either in the page or on the client
computer.
 Some Client based state management techniques are :

a) Hidden Fields
 Hidden field provides a way to store state information in the page.
 Value property of the Hidden Filed is used to get or set the value.
 Hidden fields value is stored as string i.e. plain text.
 Scope on same Page.

b) ViewState
 ViewState is used to retain value across postback.
 ViewState value is object type.
 ViewState value get stored in base64 encrypted format.
 ViewState is slower than HiddenFieldbecozViewState internally uses
HiddenField.
 Scope on same Page.

c) Query strings
 Query strings is a very common way to send data from one webform to
another.
 Query strings are appended to the page URL.
 ?(Question Mark), indicates the beginning of a query string and it's
value.
 It is possible to use more than one query string ,the first query string is
specified using the ?(question mark). Subsequent query strings can be
appended to the URL using the &(ampersand) symbol.
 Query strings are visible to the user, hence should not be used to send
sensitive information, unless encrypted.
 To read the query string value, use Request.QueryString property.

d) Cookies
 Cookies can be used to send data from one webform to another.
 Response.Cookies command is used to create cookies.
 Request.Cookies command is used to retrieve cookie value.
 Cookies are browser specific.
 Persistent Cookie : Provides Expires property where we can give
Duration to save cookie.
 Non-Persistent Cookie : These cookies expired when browser is closed.
 Cookies are by default Non-Persistent.
2) Server-Side State Management Techniques
 In Server based option, information get stored on the server side.
 Some Server based state management techniques are :
a) Session
 Session state variables are available across all pagesbut only for a given
single session.
 Session variables are like single-user global data.
 Session state variables are stored on the web server.
 The default session state mode is InProc.
 Session State variables are cleared, when the user session times out.
The default is 20 minutes. This is configurable in web.config

b) Application
 Application State variables are available across all pages and across all
sessions.
 Application State variables are like multi-user global data.
 Application State variables are stored on the web server.
 Application State variables are cleared, when the process hosting the
application is restarted.

c) Cache
 Caching is the technique of storing frequently used data/pages in
memory.
5. What are the Redirection Techniques ?
1) Hyperlink control :
 Add Hyperlink from Toolbox and use NavigateURL tag to redirect from one page
to another page of same application or different application.
 Hyperlink does not allow to write event.

2) PostBackURL :
 Add Button from Toolbox and use PostBackURL as tag.
 We can’t redirect to another application page URL.

3) Server.Transfer :
 Redirection done within same server.
 Redirection done by the server.
 URL does not change.
 It skips current page and give target page content.

4) Response.Redirect :
 Redirection done within same server.
 Redirection done by the server.
 URL does not change.
 It does not skips current page and gives target page content as well as current
page content.

5) Server.Execute :
 Redirection can be done across multiple server.
 Redirection done by the browser.
 URL get changed.
 Skip current page.

6) Window.open() :
 To open a popup window use Window.open() method.
 Window.open(URL, name, feature, replace)
 <input type = “button” value = “Open Google”
onClick = “Window.open()”/>
C# interview questions
1. Purpose of Main() method ? Scenario with writing one more main() method ?

• Every program needs an entry point to execute.

• This Main() method is an entry point where program starts its execution.

• Main() method is by default private and static.

• As C# is a case sensitive language it means Main(), main(), MAIN() these method names
are treated as different.

2. What is Datatype conversion ? What are different way of type conversion ?

• Datatype conversion is nothing but converting one data type to another data type
Example. Converting a int value to a float value or vice versa.

• There are 2 different types of Datatype conversion

1) Implicit Conversion – Compiler automatically does a conversion.


 When there is no loss of data.
 When there is no chance of exception/error

2) Explicit Conversion – When compiler fails for automatic conversion we have to do


conversion explicitly.
 Type cast operator
 Convert class operator
 Parse/TryParse operator
 Is/as keyword

If interviewer asks to explain with example then give below example

Converting from a smaller datatype to bigger datatype for example int to float in this
case there is no loss of information or there is no chance of any exception so compiler
will automatically do a conversion which is implicit type conversion.

But if we reverse this case let’s say converting a float value to int then there is definitely
a loss of information means int variable will not be able to hold fractional part and also
there is a chance of Overflow Exception. So compiler will not perform implicit conversion
and we have to use explicit cast here.
3. What are different ways of explicit type conversions ?

• There are different ways to achieve explicit type conversion –

• Type casting.

float a = 10;

int b = (int) a;

• Using of Convert class.

float a = 10;
int b = Convert.ToInt32(a);

• Using as Keyword.

object a = "some string";


string b = a asstring;

We can use Parse and TryParse methods when we need to convert a string to other
types like int, bool, float etc.

4. What is difference between cast operator and Convert class ?

• Cast operator handles the exceptions whereas Convert class does not handle and throws
the exceptions like Overflow Exception, Format Exception etc.

5. What is difference between Parse and TryParse methods ?

If the number is in a string format you have 2 options - Parse() and TryParse()

• Parse() method throws an exception if it cannot parse the value whereas TryParse()
method returns a bool indicating whether it succeeded or failed.

• We can use Parse() if we are sure the value will be valid, otherwise use TryParse()

6. What are value types and reference types in C# give some examples?

Value Type

 In value type actual value get stored on stack.


 When value type goes out of scope it will remove actual value from stack.
 Value type does not hold null values but it can achieved using nullable type.
 Ex. Integer, Boolean, Struct, etc..

Reference Type

 In reference type references get stored on stack and actual value(object) get stored on
heap.
 When references goes out of scope it will just removes references from stack and actual
value (object) is there in heap.
 Ex. String, Object, Class, etc..
7. What is Boxing and unboxing operation?

Boxing

• Converting value type to reference type called boxing. This is an implicit conversion.

int i = 10;

object o = i;

Unboxing

• Converting reference type to a value type called unboxing. This needs an explicit cast.

object o = 100;

int j = (int) o;

Boxing and unboxing are performance wise expensive processes. So it is good to avoid
boxing and unboxing if not really needed.

8. What is object type ?

• The Object Type is the ultimate base class for all data types in C#.

• When a value type is converted into object typecalled boxing whereas when an object
type is converted into a value type called unboxing.

• The object typevalues can be assigned to any other types. However, before assigning
values it needs type conversion.

9. What is var type ?

• There is no need to mention the data type when declaring a variable with var.

• We have to compulsorily initialize the value when we are declaring a variable with var.

• Also its value cannot be null at the time of initialization.


var a= 10; var z = "CSharp";

• Var type only used as local variable we cannot use it as class level fields or as method
parameters.

• The main reason behind introducing var type is the introduction of anonymous types in
C#

Interviewer might extend his question further asking what are anonymous types –

• Anonymous types allow to create a new types without defining them.

• They are extensively used in LINQ expressions whenever you want to return only a few
properties from its properties.

Ex. var person = new {Id = 101, Name = "ABC"};


10. What is difference between var and object type and dynamic keyword?

Var

• It is compile time variable and does not require boxing and unboxing.

• Since Var is a compile time feature, all type checking is done at compile time only.

• Once var has been initialized we can’t change type stored in it.

var test = 10; // after this line test has become of integer type
test = test + 10; // No error
test = "hello"; // Compile time error as test is an integer type

Object

• Each object in C# is derived from object type, either directly or indirectly.

• It is compile time variable and require boxing and unboxing for conversion and it makes
it slow.

• You can change value type to reference type and vice versa.
object test = 10;
test = test + 10; // Compile time error
test = "hello"; // No error, Boxing happens here

Dynamic

• It is run time variable and not require boxing and unboxing.

• You can assign value to dynamic and also can change value type stored in same.

• All errors on dynamic can be discovered at run time only.

• We can also say that dynamic is a run time object which can hold any type of data.
dynamic test = 10;
test = test + 10; // No error
test = "hello"; // No error, neither compile time nor run time

11. What is Array ?


 Array is a collection of similar datatypes.
 Array elements are accessed by Index.
 Index starts from 0.
 Array size is fixed and its size cannot grow automatically.
 If you try to access index which is not there it throws exception like “Index Out Of Range
Exception”.

12. Ternary operator in C#?

• Ternary operator is replacement of if else statement.

condition ? first expression : second expression;


13. What is looping in C#?

• Looping is a way to execute block of code multiple times depending upon condition.

• In looping Initialization, Condition and Updation are important things.

• There are four different loops in c#

a) while
b) do while: Gives guarantee that it will executed once
c) for: for loop is forward as well as backward also
d) foreach : foreach loop is only forward

14. What is nullable types? And Null coalescing operator ?

• In C#, types are divided into 2 broad categories.


Value Types - int, float, double, structs, enum etc
Reference Types – Interface, Class, delegates, arrays etc

• Value type does not hold null values but it can achieved using nullable type.

int? i = null;

• Nullable types is the bridgebetween C# types and Database types.

(for example, in SQL int type can hold null values and in C# by default int is non nullable.)

Interviewer might ask you what is NULL coalescing operator –

If we want to convert from a nullable type to non-nullable type then we can Null
coalescing operator.

int? i = null; // here i is nullable type


int j = i ?? 0; // as j is non nullable type it can not hold null value.

So, here if i value is null then 0 will be assign to j or else i value.

15. Purpose of break, continue, return keywords ?

• The break statement terminates the closest enclosing loop.(i.e. take cursor out of Loop).

• The continue statement skips further statement and passes control to the next iteration.

• The return statement gives cursor back to the calling method.

• If the return statement is inside a try catch block and there is finally block exists,then
finally block will be executed before control returns to the calling method.
16. What is static and instance members of class?

Static

• We use static keyword with Class and Class members.

• Static members are accessed with class name.

• There will be only a single copy of static members regardless of how many instances of
the class are created.

• When we write static keyword with class then it will restrict to create object of that
class.

Non Static Members or Instance Members

• We can access non-static members by creating the object of the class.

• There will be different copies of these members with every objects.

17. What are different method parameters in C#?

There are 4 different types of method parameters :

Pass by Value

• Any parameter value changes in called method does not reflect in calling method.

Reference Parameters

• Any parameter value changes in called method will reflect in calling method.

• It is mandatory to initialize value in calling method before passing to method.

• It is not mandatory to assign value in called method before leaving a method.

Output Parameters

• Any parameter value changes in called method will reflect in calling method.

• Internally ref and out keyword works same.

• It is mandatory to assign value in called method before leaving a method.

• It is not mandatory to initialize value in calling method before passing to method.

• By default method can return only a single value. If we want to return more than one
value from a method then we can use output parameters.
Parameter Arrays

• If a method has array as input parameter then we can use params keyword with that
parameter.

• Advantages of using parameter arrays are we can pass comma separated values instead
of creating and passing array as argument.

• Also we can call that method without passing any parameter i.e. We can achieve
optional method parameter using parameter arrays.

18. What are all ways available in C# to make method parameters as optional?

There are different ways we can make a parameter as optional parameter :

Parameter Arrays

• We can use parameter arrays to make optional parameter as it allows us to call method
without passing value for params parameter.

Default Value

• We can specify default values to parameters to make them optional.

• If we are specifying default values then it should be from right to left.

Optional Attribute

• We can use [OptionalAttribute] with parameter to make it optional.

19. What is a class?

• A class is complex custom type.

• Class contains data members and data functions.

Data Members

 Any field writing inside a class can referred as a data member.


 We can write n number of class field in class.

Member Function

 Any method or function inside a class is nothing but the member function.

20. What is Object ?


 Object is a runtime entity of class.
 We can create n number of objects of a class.

Student s = new Student();


s is a reference variable of type Student who is pointing to the object type Student.
21. What is purpose of constructor ? How it differs from normal member function?

• The purpose of constructor is to initialize class fields.

• Constructors are automatically called when we create object of a class.

• There are different types of constructors we can write inside a class like

1) Parameter less Constructor (Default)


2) Parameterized Constructor
3) Copy Constructor

• Compiler automatically provides a default parameter less constructor but if there is


parameterized constructor then we have to explicitly write default parameter less
constructor.

22. What is purpose of static constructor ? When it will get called?

• Static constructors are used to initialize static fields of a class.

• Static constructors are called only once regardless of how many instances of the class
are created.

• Static constructors are automatically called when

I. We access static member.


II. We create object of class.

23. What is use of this and base keywords?

• this keyword refers to current instance of a class. If we want to access any instance
member of class we can access them by using this keyword.

• base keyword is used to refer the instance of base class. If we want to access or call
constructor or any other instance member from base class we can use base keyword.

24. What is OOPS ? What are the main pillars of OOPS ?


 OOPS stands for Object Oriented Programming System.
 The main pillars of OOPS are
1) Inheritance
2) Polymorphism
3) Abstraction
4) Encapsulation
25. What is inheritance what are uses of inheritance?

• Inheritance is the ability to create a class from another class when there is a is a
relationship.

• Inheritance provides us code reusability means we can use the existing properties and
functionalities of the base class into derived classes.

• Inheritance provides a specialization it means a derived class is a specialized class which


has all properties of base class as well as its own properties.

• Inheritance provides extensibility it means we can easily plug a new type without
affecting the existing functionalities.

26. What is polymorphism ? What are types of polymorphism ?

• Polymorphism is nothing but a single thing having multiple forms.

• There are two types of polymorphism

1) Compile time Polymorphism


– Method Overloading
–Operator Overloading

2) Runtime Polymorphism
– Method Overriding

27. What is method overloading? On what basis a method can be overloaded?

• Method overloading is a compile time polymorphism means it checks at compile time.

• Same method name having different forms called method overloading.

• Method can be overloaded on the basis of

1) Number of Parameter
2) Types of Parameter
3) Order of Parameter
4) Kinds of Parameter
 Method cannot be overloaded on the basis of

1) Return Type
2) Ref and Out Keyword
3) Using Params
28. Can method overloaded on basis of just return type ? if no, then why?

• No. Method cannot be overloaded just on basis of return type.

• Return type is not considered in method signature while method overloading.

• This behaviour is by design and it is because to avoid confusion of a developer that what
will be the output of the method if the method is same and just changed with the return
type.

29. Can method overloaded with out and ref?

• Method cannot be overloaded just on basis of ref and out keyword.

• At compile time both ref and out refers as same and internally both works same.

• So compiler does not allow us to overload a method just on basis of ref and out
parameter.

30. Can method overloaded with params (parameter arrays), why?

• We cannot overload a method just on basis of params keyword.

• Compiler does not find any difference in normal array parameter and a parameter array
at compile time.

31. What is method overriding? Why it is called runtime polymorphism?

• If base class and derived class contain same method then base class reference variable
pointing to a derived class object will call derived class override method.

• In order to override a method in derived class that method should be virtual or abstract
or override in base class.

• Method overriding is called as runtime polymorphism because which method will get
called is decided at runtime based on the type of object.

32. What is difference between Method overloading and Method overriding?

• Method overloading and method overriding both are the types of polymorphism.

• Method overloading is a compile time polymorphism because at compile time only it is


known that which overloaded method will get invoke on execution.

• Method overriding is a runtime polymorphism because which method will get called is
decided at runtime based on the type of object.
33. What is method hiding ? Scenario of object creation and calling methods.

• If base and derived class contain same method then a base class reference variable
pointing to a derived class object will call base class method is called method hiding.

• If we don’t provide new keyword in derived class method then compiler will gives us a
warning that if hiding is intentional then use new keyword.

• We use new keyword in derived class method because method hiding is intentionally.

34. What are Properties ? Why should we use properties ? What is auto-implemented
properties?

• Properties are used to encapsulate and protect the private fields.

• We can write custom logic to validate the user data before it is actually assigned to or
retrieved from private fields.

• Using get and set access modifierswe can create Read Only, Write Only and Read Write
Properties depending on our requirement.

• Auto implemented properties, with this feature we do not need to declare a separate
private field for a property.

• Framework automatically creates a private field for the declared property.

Ex. Public string Name{ get; set; }

35. What are indexers?

• Indexers are used to design our indexed based class objects just like an array.

• We create Indexers by using “this” keyword.

• We can overload the indexers just like we overload a method.

• In real time, Session object, Data Table object, Rows Object uses indexers to access the
values.

36. What is difference between class and struct?

• A struct is a value type and they get stored on the stack whereas class is reference type
and they get stored on the heap.

• Struct gets immediately destroyed from the memory once they go out of scope whereas
for class only reference variable gets destroyed after it goes out of scope and the actual
object get released by garbage collector.

• Struct cannot have destructors whereas a class can have destructors.


37. What is encapsulation and abstraction ? When abstraction and encapsulation comes in
project development ?

• Abstraction is a concept of showing necessary information to outside world.

• Encapsulation is a concept of hiding unnecessaryinformation from outside world.

• Abstraction comes at design level whereas Encapsulation comes at implementation


level.

• If we talk in terms of coding perspective, public fields shows abstraction and private
fields shows encapsulation.

38. What are interfaces ? What are advantages using interfaces ?

• Interfaces are just like classes but they just have declarations and not implementations.

• Object of interface is not possible but an interface reference variable can point to a class
object which implements that interface.

• If a class implementing an interface it is mandatory for that class to provide


implementation to all the interface members.

• By default we can’t use any access specifier for interface members and we cannot
specify even a public

• Multiple class inheritance is not possible in C# but we can achieve it with interfaces.

• Interfaces are used to implement SOLID principles and Design patterns.

39. What is explicit interface implementation ? When there will be need of implementing
interface explicitly.

• When we are implementing 2 or more interfaces in a class and those interfaces are
having same method signature.

• Then we have to implement those interfaces explicitly in order to give implementation


to all of the interfaces.

• We have to prefix interface name with method namewhile implementing interface


explicitly.

• This implemented methods by default public. We cannot specify any other access
modifier even a public.

• To call particular method we have 2 approaches –

• Creating interface reference variable pointing to class object

• Creating a class object and then type casting as interface and invoking a method.
40. What are abstract classes ? Can it be instantiated?

• Abstract classes are created with abstract keyword.

• Abstract classes are used as base types.

• They are just like concrete classes but they contain both abstract and non-abstract
members.

• Abstract members means members with just declarations.

• Object of abstract class is not possible but an abstract class reference variable can point
to a derived class object.

• When we inherit abstract class then it is mandatory to implement abstract members in


derived class.

41. Can abstract class have a constructor? When it will get called?

• Yes. Abstract class can contain constructors.

• Abstract class constructors get called before derived class constructor call.

42. What is sealed class?

• Sealed class are prevented from inheritance it means Sealed classes cannot be used as
base class.

• Rest of things are same as normal class.

43. What is difference between interface and abstract class? When to use interface over
abstract class or vice versa.

• Interface cannot have definition for any of its member whereas abstract class can have
definition for its members (non-abstract member).

• Interfaces cannot have fields whereas abstract class can contain field.

• By default access specifier for interface members is public and we cannot specify any
other even a public whereas abstract class members access specifiers can be changed.

• If there is situation that all the derived classes has different implementation but we have
to provide same method signature then we can go with interfaces whereas if there is a
situation that few of the derived classes sharing same implementation then we can think
of using abstract class instead of interface.

• In interface multiple inheritance is possible whereas in abstract class multiple


inheritance not possible.
44. Why multiple class inheritance is not possible In C# ? How to overcome it.

• Multiple class inheritance is not possible in C# it is also called as Diamond Problem.

• Let’s say we have one class A which is derived by two classes B and C. Class B and C has
overridden method which was marked virtual in class A.

• Now if we derive class B and C in a new class D and we are not providing any
implementation in class D.

• So, if we create an object of class D then which method implementation should get call
here from class B or class C. There will be an ambiguity in calling 2 different copies of
overridden method. This problem is called as Diamond Problem.

• We can achieve multiple class inheritance using interfaces. [Interviewer can ask to write a
code snippet here.]

45. What are all access specifiers in C# ?

There are 5 different access modifiers available in C#.

• Private – Its accessibility is only within a containing type.

• Protected – It is accessible within containing type as well as in derived type in same


assembly or from different assembly.

• Public – It is accessible anywhere in the application.

• Internal – It is accessible anywhere in the same assembly.

• Protected Internal – It is accessible anywhere within same assemblyas well as in derived


type in same assembly or from different assembly.

46. What is default access specifier for type and type members?

• Default access modifier for a type is internal.

• Default access modifier for types member is private.

47. What is internal and protected internal access specifiers?

• Internal access modifiers are accessible from anywhere within the same assembly. We
cannot access them outside assembly.

• Protected internal is can be considered as combination of protected and internal access


specifiers means it is accessible anywhere from the containing assemblyas well as in
derived type in same assembly or from different assembly.
48. What are partial classes and rules to create partial classes?

• Partial classes allow us to split a class into 2 or more files.

• When the application is compiled, all these parts then combined into a single class.

Rules :

• All parts should have partial keyword.

• All parts should have same access modifiers.

• If one part is marked abstract then entire type is considered abstract.

• If one part is marked sealed then entire type is considered sealed.

• Multiple class inheritance is not possible in C# so different parts should not inherit
different base classes.

49. What are partial methods? Anything can be asked related to rules followed during
creating partial methods?

• Partial class can contain partial methods.

• Partial method created using partial keyword and it has two parts – the declaration and
the implementation.

• Partial methods are by default private. We cannot specify any other modifier even
private.

• Partial method implementation is optional. If we not provide implementation then


complier removes its declaration as well as all the calls.

• Partial method return type must be void. Giving any other type gives compile time error.

50. Why there is need of exception handling?

• Exceptions are nothing but runtime unforeseen errors of an application.

• It is always a bad practice in showing yellow screen to end user which contains some
application specific information.

• This information is meaningless for a normal user whereas useful for a hacker to hack
your application.

• So it is always recommended to do a proper exception handling.


51. Can a try block have multiple catch block ? Scenario of using Exception classes while
using multiple catch blocks ?

• Yes. One try block can have multiple catch blocks.

• But as all exception classes are derived from Exception base class we have to specify
Exception class in the end catch block. If we specify it at the top then we will get
compiler error.

52. What is purpose of finally block? Scenario for executing return statements.

• Finally block is guaranteed to be executed in both the cases if there is error occurs or
not.

• Also it gets executed if there is any error occurs in catch block.

• So we can use finally block to close the open connection or if we want to explicitly free
the resources.

[Scenarios can be asked based on return statement or using Response.Redirect, Server.Transfer,


Server.Execute by writing them in try catch and finally blocks.]

53. What is difference between Convert.ToString() and ToString() methods?

• Convert.ToString() handles NULL whereas ToString() doesn’t and it throws


NullReferenceException.

54. What are enum? What are usage of enum?

• Enum is the best replacement of an integral constant.

• Default underlying type of enum is int.

• Enum are value type.

55. Can we customize values in enum? What is default start value to enum?

• Yes we can customize the values of enum.

• The default start value of enum is 0.

56. What is default underlying type to enum? Can we change its underlying type to some
other type?

• Default underlying type of enum is int.

• We can anytime change underlying type to any other integral datatypes like byte, short
etc depending on the size we want to store.
57. What is difference between enum and Enum class?

• Enum is a keyword use to create enumerations whereas Enum class contains static
methods like GetValues(), GetNames() which can be used to list enum underlying type
values and their names.

58. What are all default methods comes with every type in dot net? From where they are
derived? Can we override them?

• All types in dot net directly or indirectly derived from Object class

• All these default methods are :

1) GetType()
2) ToString()
3) Equals()
4) GetHashCode()

 We can override ToString(), Equals(), GetHashCode() methods because virtual keyword is


in there method signature.

59. What it GetType() method?

• Gives the type of the current instance.

int number = 10;


Console.WriteLine(number.GetType());O/P -> System.Int32

60. What is difference between typeof and GetType() method?

• Both the methods are used to get the type of the current instance.

• For typeof method type is known as compile time whereas GetType() method is used to
get exact type of current instance at runtime.

• GetType() method is invoked with instance whereas typeof method expects the type.

61. Why there is need of overriding ToString method?

• When we call ToString() method with built-in types it gives us the string representation
of that current type.

• But if we call ToString() method with Complex types like Customer, Employee it gives us
the fully qualified name of the type that means namespace name followed by type
name.

• So to give a meaningful string representation for complex types we can override


ToString() method.
62. Why to override Equals() method? Is there is any warning/error associates with just
overriding Equals method? If yes, how to fix it?

• Equals() method works fine with built-in types but when it comes to complex types it
checks only reference equality and not value equality.

• So we can override this Equals() method to check value equality for complex types.

• There is one warning when we override Equals() method and that is we have to override
GetHashCode() method also. This method is helps to generate unique hash codes.

63. Can we overload == operator?

• All arithmetic operators works fine with built-in types.

• But when we use == operators with complex types it just check reference equality and
not value equality.

• In order to achieve value equality we have to overload == operator.

64. What are Static, Constant and Readonly ?

Static

 Static fields have a single copy regardless of how many instances of the class are created.

 They are accessed with class name.

Constant

• Constant variables are used to create constant fields.

• It is mandatory to initialize the value at the time of declaration.

• Constant variables value cannot be changed throughout the program.

• They are by default static.

Readonly –

• Readonly fields are also similar to constant variables but we can change its value at
runtime through non static constructors.

• It is also not mandatory to initialize value at the time of declaration.

• We can also have static readonly fields in which we can assign value at runtime through
static constructor but only once.

65. What is use of yield keyword?

• Yield keyword helps us to do custom stateful iteration over .Net collections.


66. What are delegates? Why delegates are type safe?

• Delegates are type safe function pointers.

• Delegates signature should get match with method signature that’s why it is called as
type safe.

• Delegates allow methods to be passed as parameters.

• Delegates are used to define callback methods.

67. What are types of delegates? Predicate, Action and Func Delegate?

Basically there are 2 types of delegates

Singlecast delegate – Delegate pointing to a single method.

Multicast delegate – Delegate Pointing to multiple methods.

Apart from these types we have few generic delegates which extensively used in LINQ
methods.

Predicate Delegate – Delegate has type T as input parameter and bool as return type.

Action Delegate – Delegate has type T as input parameter and void as return type.

Func Delegate – Delegate has type T as input parameters and T as output parameter.

68. What are multicast delegates?

• A delegate pointing to multiple methods called as multicast delegate.

• It will help to call multiple methods on a single event.

• If the methods has return type or out parameter then the last method value get
returned from delegate.

69. What is generics? Name some generic collections and non-generic collections?

• Generics allows us to design classes and methods decoupled from the data types.

• Which avoid boxing and unboxing operations and offers better performance.

• List<T>, Dictionary<T>, Stack<T>, Queue<T> are few examples of generic collections


classes.

70. What is Collection class? Name some Collection class?


 Collection classes are specialized classes for data storage and retrieval.
 The purpose of collection class is allocating a memory dynamically to element and
accessing list of items on the basis of index.
 Arraylist, HashTable, Stack, Queue are few examples of collections classes.

71. What is difference between ArrayList and List<> ?

• ArrayList is a non-generic collection class whereas List is a generic class.

• ArrayList is object based and it is not type safe because it is associated boxing and
unboxing operations whereas List is type safe and there is no boxing and unboxing
operations which actually helps to improve system performance.

72. What is difference between HashTable and Dictionary<>?

• Both Hashtable and Dictionary are Key Value Pair collections.

• HashTable is a non-generic collection class whereas Dictionary is a generic class.

• HashTable is object based and it is not type safe because it is associated boxing and
unboxing operations whereas Dictionary is type safe and there is no boxing and
unboxing operations which actually helps to improve system performance.

73. What is advantage of generics collections over non generic collections?

• Generic collections are type safe because there is no boxing and unboxing operations
which actually helps to improve system performance.

74. What are anonymous methods and extension methods?

Anonymous methods :

• Anonymous methods are nothing but methods without name.

• Anonymous methods allows us to create delegate instance without having a separate


method.

• Anonymous methods are created using delegate keyword.

Extension Methods :

• Extension methods are used to extend the functionality of any existing type.

• These methods are public static methods and its first parameter is prefixed with this
keyword.

• It is mandatory to write extension method in public static class.

75. What is lambda expression? Interviewer can ask to write a small program using
lambda expressions.

• Lambda expression are simplified way to write LINQ queries.

• Lambda Expressions are more convenient than anonymous methods.


76. What is difference between anonymous method and lambda expression?

• Lambda expressions are just new way to write anonymous methods.

77. What is Tuple?

• Tuple is collection of heterogeneous types of items.

• We use tuple to return multiple values from method.

78. What is early binding and late binding?

• Early binding gives errors at compile time with late binding there is a risk of runtime
exceptions.

• Early binding is much better for performance and should always be preferred over late
binding.

• Late binding is used only when we are not aware about the objects at compile time.

79. What is eager loading and lazy loading in C#?

• In eager loading, all the objects are initialized in memory as soon as the objects are
created.

• In Lazy loading, we delay the loading of the objects until the point where we need it.

• We have System.Lazy class to implement lazy loading.

80. Questions on interface like IEnumerable, IQuerable interfaces?

• We use IEnumerable for in memory collection like List, Dictionary whereas we use
IQuerable for remote servers like SQL server.

• IEnumerable supports lazy loading whereas IQuerable supports eager loading.

81. How to restrict a class for instantiation?

• We can restrict a class for its instantiation by making that class as a static class or we can
write a private constructor in that class.

82. Private constructor, how to initialize? where it is used? what is singleton?

• When we write a private or protected constructor in a class we cannot create instance of


that class from outside of that class.

• We create the instance of a class in that class itself. We use public static method to
expose the instance.

• Singleton pattern ensures that there will be single copy of object throughout the
application and it provides a global point to access that instance.
83. What is difference between Static class and a Singleton class?

• A Static class contains only static members whereas in Singleton class we can have both
static and non-static members.

• Singleton class can implements interface whereas static class cannot implement
interface.

• We can dispose the object of singleton class but not of static class.

84. How to create a instance of singleton class?

• Singleton class exposes a single instance through a public static method.

classSingleton

{
privatestaticSingleton _instance;

private Singleton()
{
}

publicstaticSingleton Instance()
{
if (_instance == null)
{
_instance = newSingleton();
}

return _instance;
}
}

• We can write below code to create instance of singleton class.

Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();

[Please note that here s1 == s2 will be true as both are referring to same object.]

• Inheritance scenarios - like multilevel inheritance with new and override keywords.

• Scenario based questions can be asked here –

• Let’s say there are 3 classes A, B and C. Class B is inheriting class A and class C is
inheriting class B.

• There will be a method which will be virtual in class A and it will be hidden by class B and
C with new keyword. Then which methods will get called with below set of objects.

• A a1 = newB();
• A a2 = newC();
• B b1 = newC();

85. Same example can be replaced with override keyword or combination of new and
override methods. We have to think on the type of object and give the answers.

86. What is Association, Aggregation and Composition in C#?

Association

• Inheritance defines the ‘is a’ relationship just like Association defines ‘has a’relationships
between objects.

• In short, Association means an object “uses” another object.

• We can define one-to-one, one-to-many, many-to-one and many-to-many objects


relationships.

Aggregation

• Aggregation is a special type of association.

• It is a direct association among the objects.

• For example, departments and employees, a department has many employees but a
single employee is not associated with multiple departments. In this case both the
objects have their own life cycle.Employees may exist without a department. Here,
department can be called an owner object and the employee can be called a child
object.

Composition

• Composition is special type of Aggregation.

• In this type of Aggregation the child object does not have their own life cycle. The child
object's life depends on the parent's life cycle. Only the parent object has an
independent life cycle. If we delete the parent object then the child object(s) will also be
deleted. We can define the Composition as a "Part of" relationship.

• For example, the company and company location, a single company has multiple
locations. If we delete the company then all the company locations are automatically
deleted. The company location does not have their independent life cycle, it depends on
the company object's life (parent object).
Experience Companies

Projects Handled:
College Interview Management System
Cosmetic Health Insurance System
Hospital Management System

Company Name : Square Vision Technologies

Location : 3rd Floor, LaxmichayyaNiwas, Behind Bharati Bank, DhayariPhata,


Pune 411041

Founder :Shivkumar

Founded when : 2012

Employee Strength : 100 to 150

Company website :http://squarevisiontech.com

Lead &Manager name , email, contact:VikulRathod

Email : [email protected]

Mobile. 8956890522

HR Manager :Shivkumar

Email: [email protected]

Mobile: 9890055031

***************************************

Project Handled:
Print Shoppy
Move Goods

Library

Company name :Avapya web service

Location :Avapya Enterprises: S. No. 29, House No. 5/770/92, Near Jagtap Dairy,
Vishal Nagar, Pimple Nilakh. Pune - 411027

Registered Office: Plot no. 1/21, ChipWell Knives, MIDC – Ambad, Nasik - 422010

Founder : Rahul Kashelani

Founded when : 2011


Employee Strength : 100 to 150

Company website :http://fin.avapya.com

Lead &Manager name , email, contact: SanketThool,

Email: [email protected]

Mobile :9730225992

HR name : Rahul kashlani

Email: [email protected]

Mobile: 9923 456 000

***************************************

Questions:
1. Are you on permanent payroll or are you permanent employee?
- yes I am on permanent payroll for this company.

2. Are you working on contract basis?

- No. I am working on permanent payroll.

2. Is your salary fixed? Or is there any incentive or variable component in your CTC?
- my salary is fixed and there is no incentive in my current CTC.

3. Are you in Pune? or are you working from home? How are you currently working?
- all employees are working from home now a days since March. Company has
already informed to work from home till Mar 2021. In March they will going to inform
about our office resume or else they are going to extend wfh for all employees.

4. What is your notice period?


- my official notice period is 1 month. But considering the current situation it can be
negotiable to 10 to 15 days.

5. How soon you can join us?


- as of now my project is stable and all development work is already done. So I am
not holding much work now and manager asked me to wait till new assignment.

6. Why are you looking for job change? Or why are you switching your job?
- there is no specific reason but I have already completed lot of experience with this
company and team. Now want to explore work with new company so that I can
explore different project domain along with some new technologies.

7. Are you ready for relocation?


- yes there is no problem for me to relocate. I am ready to work from any given
locations.
8. How are you delivering your work as you all are working from home? Or how your
team is collaborating with each other?
- we use skype for all our meetings also if needed we share our screen to showcase
any issues. Apart from that everything is going smooth as we do in office.
Sometimes there were some situations where because of network issues couldn't
able to join meeting but anyways I got that update from team member once I get
online.

9. Will you able to join in 2 -3 days?


- well, I don't have any issues but I need to check with my manager and HR then
only I can confirm you on this. But definitely I will try from my end to get early
release.

10. Do you have pf account?


- no in my company I have not opted for pf. But if you have provision for pf in your
company I will opt that pf facility.
(Please note even if you have pf account say no. No need to provide pf account. It's
not mandatory. But if you want you can provide UAN after joining)

11. How you get your salary ? Or in which bank you get your salary?
- salary is deposited in my account. You can tell your bank name.

(Cheque Book, ATM, Internet bank Login)

12. Will you able to provide your bank statements where salary credit is reflected?
- sure I will do that. There is no problem for me to share bank statement with you if is
required. I will submit all required documents with you once I receive offer from you.
( Say yes, as we can generate and provide bank statements. So say simply yes.)

13. Do you have form 16 with you?


- as of now I have not received form 16 from my company once I receive I will
provide you form 16 document.

In that case can you provide your previous year form 16?
- sure, I will do that give me sometime I will forward it to you on your email.
( Say yes, they are just checking how confident you are in giving answers. If needed
we will provide but remember its still not mandatory they just check whether you are
a genuine employee or not. Everything is depends on how you are speaking and
how confident you are.)

14. Do you have personal laptop?


- yes I have my personal laptop.

15. Are you working from office device or your own laptop?
- company provided me office laptop and working on office laptop.

16. Will you able to join and start working from your own laptop?
- sure no issues. Though I cannot use my office laptop as I need to deliver it to my
office on my last working day I will try to work on my own laptop till the time I receive
office laptop from your side.
17. Are you ready to join online?
- yes, as per your instructions and guidance I will be able to complete joining
formalities through online.

18. Give your 2 professional references? Or give me 2 contacts with whom your
worked in past?
- give 2 names along with their mobile from your own team group. ( Just inform those
2 team members before you provide their contacts to HR )

***************************************

Few Terms in short:

1. Offer letter or appointment letter or joining letter or Deputation letter


- company gives this when we get selected to join that company. Where they
mention all joining details, policies along with salary breakup.
( Please note this format can be different so don't get surprise by looking at formats )

2. Salary slips or payslips or salary certificate


- document which you get every month which showcase monthly payment details
along with breakup.

3. Increment letter or hike letter or appraisal letter


- document which you get after salary increment. Mostly company follow a appraisal
cycle where they increase pay(salary) of an employee. In our case hike month is
December of every year.
For ex. Dec 18, Dec 19, Dec 20 etc

Dec 2021 increment it got postpone to June 2021

4. Resignation acceptance or resignation letter


- this will be a proof which means you resigned from your current company. It will be
simply an email copy where you have sent resignation email to your manager and
HR and your manager has accepted your resignation and mentioned last working
day.
( We resign when we get offer letter from new company or whenever we want quit
job from that company )

5. Experience letter or reliving letter or Experience Certificate


- these can be two separate documents or one single document. This document
shows total experience means joining date and last day of yours in that company.
This will get on or after your last working day in that company not prior to that.
( You will get your experience letter on last working day before joining your new
company )

6. Resignation date
- date when you resigned from company. It means you are giving a formal notice of
leaving company.
7. LWD - Last Working Day
- day when you will be actually seperated from the company

8. Notice Period - NP
- every company has a policy where company ask employee to stay after your
resignation day. NP can be different in companies it can be 1 month 2 month 3
month or 15 days also it totally depends on company policy. NP is there because
once you resigned you can deliver KT( Knowledge Transfer ) to your colleague who
can work further on that project once you leave company. In simple words notice
period is time between resignation day and last working day.

9. Cancelled cheques
- some company may ask for cancelled cheque as security or bank details
confirmation so that they can deposit salary in your account.

10. Salary account


- where salary gets deposited. Not necessarily it should be salary account only
because salary can be credited to savings account also. When you join new
company they will open salary account for you where they have contracts.

11. PF
- provident fund
It's a government policy where they ask to pay 10 to 12 percent of basic pay as PF.
There are two components in PF. Employer and Employee provident fund. Both are
deducted from employee account only.
( Please note company does not use PF for background verification (BGV))

12. Bank statements **


- company ask for bank statements for background verification as they want to
doubly sure about your employment. Anyways no one can go and check account
details of others. So do not worry if company is asking multiple times for bank
statement we will generate and provide them they will just keep it as documentation
purpose.

13. LOA - Letter Of Authorization **


- this is a document where you need to sign. Once you sign on it, it means you are
giving them rights to check your background including your bank also.

14. Form 16 **
- this is a proof which company gives to employee for tax deduction. Actually
company deduct tax from employee and pay to government. Obviously employee
also wants to check whether company has paid tax or not for that purpose we get
form 16. Where we can see all paid taxes which company deducted from our
monthly salary. It's a government document.

15. ITR - IT Return (CA Refer – nominal charges 500/-)


- there are chances that in financial year we pay more or less tax than the defined
tax slab. There is an opportunity to pay or get refund of paid tax. After completion of
financial year we can file ITR on government ITR portal. We get a softcopy of ITR
once we file ITR.
( Financial year - 1st April to 31st March

Filling ITR is mandatory even if you don't have form 16 )

16. CTC - Cost to company


- your annual package
( 6 LPA - 6 Lacs Per Annum )

CCTC - Current CTC ( in current company )


ECTC - Expected CTC ( your expectations from new company ) (> 30%)

17. Total Experience


- your total working experience. It can be from any fields it means combination of all
your work profiles.

18. Relevant Experience


- Your working experience in specific work profile

For ex. If someone worked as professor for 3 years and then he worked as
developer for 5 years.

Then for him, total experience is 8 years and relevant experience in dot net is 5
years.

19. Variable pay or Incentive

- this is the amount from our package which we don’t get every month.

This amount we receive once in year or after six months or quarter.

In my CTC there is no variable pay or incentive. My CTC is fixed.

20. UAN?

- Universal Account Number – generate using PAN and Adhaar

- Under this UAN all your PF accounts gets linked.

21. How much chain of Company architecture tells to interviewer means CEO,CFO,director,
associate director, manager, associate manager,team

Trainee -> Software Engineer -> Senior Software Engineer -> Tech Lead -> Manager ->

Senior Manager -> Director


On joining company gives employee

 ID card
 Access Card -> using this card you can access to office premises

Office timing – 9:30 AM to 6:30 PM


Entity Framework Question-Answer
1. Entity Framework and its approaches ?
 Entity framework is used to communicate with the database.
 Entity Framework approaches are
1) Database First
- Database first approach creates the entity framework from an existing
database.
2) Code First
- Code first approach create database that doesn’t exists.
- It can also be used if you have an empty database and then code first will add
new tables too.
3) Model First

2. Which approach you have used in your project and explain it ?


 We used Databasefirst approaches as per requirement.

3. What is difference between ADO.net and Entity Framework ?


 ADO.net creates bunch of data layer code whereas Entity Framework doesn’t create
bunch of code.
 ADO.net is faster than entity framework because entity framework uses ado.net code
behind so entity framework requires some extra time cost.

4. What is DbContext ?
 DbContext is an important class in entity framework.
 DbContext is a bridge between entity classes and database.
 DbContext is the primary class that is responsible for interacting with the database.
 DbContextSavechanges method executes Insert, Update and Delete commands to the
database.

5. What is Dbset ?
 The context class derived from DbContext must include the Dbset type properties for
the entities which maps the database table and views.
1. What is DOM ?
 DOM means Document Object Model.
 DOM represents logical tree structure of HTML elements.
Window

Document

Html

Head Body

↓ ↓
Title Script Input Button

2. What is DOM property ?


 DOM properties are values of HTML elements that you can set or change.

3. What Z index in CSS ?


 Z index specifies the stack order of an element.
 An element with greater stack order is always in front of an element with a lower stack
order.
 z-index only works on positioned elements.
 If we want add background image then we can use Z index.

4. What strict mode in Javascript ?


 Used to generate silent error.

5. What is View Port ?


 The viewport is the user's visible area of a web page.

6. What is Media Query ?


 Media query is CSS property used for Responsive Web Design.

7. What is Responsive design ?


 Responsive web design is about creating web pages that look good on all devices.
 A responsive web design will automatically adjust for different screen sizes and
viewports.

8. Difference between local storage and session storage ?


 Local storage is similar to session storage.
 But the data in local storage doesn’t expire whereas data in session storage is expired
when page session ends.

9. What are the file in local storage ?


 Browser setting, Browser extensions.
Interview Preparation
Q. Introduce yourself?
 My name is Aniket Vitthal Sawant-Kedar.
 I have been working with Avapya Web Service.
 I have 3.10 years of experience as Dot Net Developer.
 In my experience, I have handled three different projects.
 In our project we use Asp.net, Asp.net MVC, Web API, Ado.net, Entity Framework,
JavaScript, jQuery and LINQ in that.
 We use C# as language and SQL as database.
 I also worked on coding standards.
 I have always met the project deadline for which I had to work late hours and
weekends.

Q. What roles and responsibilities you are handling?


 My roles & responsibilities is to develop the codeto do different functionalities using
C#, MVC and WebAPI and delivering that code within the time by understanding the
project requirement.
 And i also involved in database table designing and writing store procedures in SQL
Server.
 I do analysis for my assigned user stories and proactively check all other user stories
also.
 I participated in daily standup meeting, sprint meeting, planning meeting and
retrospective meeting.

Q. Explain your project flow?


Q. Describe your project, your skills?
Q. Tell me about your project?

Ready Set Move


Our website provides on demand or same day delivery services by
connecting user to driver. In our project there three types of roles Admin, Driver and
User.

User

 When user login into system with his credentials then he can search for vehicle.
 For search of vehicle user has to enter pick & drop location, departure time and
approximately weight for material.
 Depending upon these information user can see vehicle type and its availability.
 After selecting vehicle type user can see estimated time and cost for that trip.
 If user clicks on Place Order then he has to pay 10% advance money through net
banking and remaining in cash or net banking after delivery.
 After that user can give feedback about that driver.

Driver

 Driver can register online on website or offline in company office with required
documents.
 When driver login into system with his credentials then he can see nearby trips.
 Driver can accept or reject that trip.
 Driver can update his status active/inactive.
 Driver can also feedback about user.
Admin
 When admin login into system with his credentials then he has access to all data.
 Admin can see how many active delivery in progress, completed or cancelled.
 Admin can activate driver by checking all its document.
 Admin can access to manage user and driver.

To develop this application we have used C#,MVC 5, WebAPI 2, LINQ, Entity


Framework, Javascript,jQuery, HTML, CSS, SQL server

Q. Explain your Project architecture?


 My Application has 3 tier architecture.
 In that we used MVC as PresentationLayer i.e. UI, WebAPI as Business Layer and Sql
server as Database Layer.
 The MVC layer not directly communicate with the database.
 The MVC layer is communicate with the Web API layer for that we have used
Repository pattern to call APIs.
 When API gets requests from the MVC layer, the API repositories interacts with the
database layer.
 All the calls from MVC layer are transferred to the database through the API project.
 The API project which is hosted on internal server of my client and only the MVC
layer is visible to external users.

Q. What you did in your project?


 In our application, basically I worked on all different layers.
 I worked on database, MVC and Web API also.
 In database, I worked on table design, writing store procedures and views,
optimization of queries.
 In MVC, I worked on Forms Authentication, Validations, Consuming Web API in
controller.
 In Web API, I worked on writing methods for accessing data from database and also
testing of API methods using Postman.

Q. How you deploy your code?


We deploy our code on Dev server.

Q. Tables and store procedures,Controllers

Around 35 to 40 tables
Ex. rsm_Role, rsm_User, rsm_Admin, rsm_Order, rsm_VehicleType, rsm_VehicleOwner,

Around 140 to 150 stored procedures


Ex: uspGetOrderList, uspGetAllUserList, uspGetVehicleType, usp_InsertUser,
usp_UpdateUser

Around 22 controllers
Ex.
Q Team size-

Team size- 12
Dot net developer- 6(Me, Arjun Kshirsagar, AkshayDikare, Balaji Jadhav)
Tester – 8
Deployment – 2
Team lead – 1 (Laxmikanthemke)

Q. What is domain of your project?


e-commerce

Q. Who is your client?


Our Client is Australia based Client

Q. How your daily work start in your office?


 Firstly we have attend the daily stand up meeting.
 Then we have to finish the taskswhich are assigned to us. Sometimes we have to
attend project meetings, also some timeswe have to communicate with client.

Q. Events in company - apart from development what extra things happen in company
1. Apart from development we have to attend Project meeting. Also we have discussion with
manager
2. Sometimes company arrange sessions on any technical subject
3. Company organizeAnnual functions also.

Q. Do you communicate with client or not?


No we don’t communicate with client,our BA communicate with client to get new the
requirement or if they want any modification in the existing projects.

Q. Do you know about Agile process?


Yes. I worked in agile process in my previous organization. We used Agile scrum. Where we
worked in 2 week sprint. Sprint is duration which we will deliver something to client. Every
sprint has Release where we delivering product to client. Agile scrum has scrum meeting.
Agile scrum have-
1.Product owner- Business analyst- helps to understand the requirement
2.scrum master- Manager
3.scrum team – developers, testers, leads etc.

Q. What was sprint duration in your project?


In my previous organization there was 2 week sprint.

Q.What is your designation in your team?


As a software developer / programmer analyst.

Q.What you did in your project apart from coding? You only do coding? Any other
achievements, innovation
Apart from coding we have to create business requirement understanding document,
Estimation timeline sheet for all the task, project document, if we created any services then
we have to create service request- response documents. I fixed the bugs which are raised by
testers.
Q.Which service you have used in your project?
We used webApi

Q. Name all services which you have created in your project?

Q. What type of difficulty you find with your process?


Q. What difficulties & challenges you faced during your work?
Yeah, while doing one task I felt it was challenging, actually in our database there were 4
tables named tblSurgeon, tblCoverageGroup, tblCategories and tblSubCategories, so my
challenge was I had to get all these tables data into list and display the list on UI and I had to
pass only PatientId and Patient table has no information about these tables except it has
surgeonId as foreign key. So for that I used temporary tables in sp to display list on UI.

One more challenging task was to work on email integration,before that I had never worked
on this, but I able to work on that by learning how to send mail to user, we have used SMTP
class and ASPOSE for pdf generation.

Q. Where you have used design patterns in your project?


Q. Where you have used Singleton design pattern in your project?

We have used Singleton design pattern to share common data access throughout the
application. In our project, on most of the modules we display report. To generate report we
have to fetch the data from database. So we have written all code which interact with
database in one singleton class and we used that singleton object in all modules.

Q. what was your main role in your project?


As a software developer I have to work on developing the web portal and to create web apis.

Q. Where you have used interfaces in your project?


To implement repository pattern we have used interface.

Q. Where you have implemented SOLID principles in your project?


We implemented SRP, OCP in our project. In my web project every class has his separate
single functionality. As per OCP we implemented new changes by creating class and
inherited in existing class.
We have used Dependency Injection pattern. Basically it tells about the process of
injecting the object rather than depending on the entities. So, in our project we have policy
and in the policy controller we define the IpolicyRepository interface and this interface is
going to inject to the constructor of the controller. i.e. we have followed constructor
dependency. The main purpose of DI it will decouple components And object creation
internally it will take care.

Q. Where you have used OOPS pillars in your project?


Q. Where you have implemented encapsulation, abstraction in your project?
Q. Where you have used inheritance in your project?
Q. Where you have used method overloading in your project?
Q. Where you have used method overriding in your project?
Polymorphism-
We implemented method overloading by creating same method with different parameters.
For eg. In our project we created two methods to get the patient details from surgeons. First
we get the all patientinfo from surgeonID and another method get all patientinfo from
Surgeonname.
Public ActionResult GetAllPatientInfoFromSurgeon(int SurgeonID){}
Public ActionResult GetAllPatientInfoFromSurgeon (string surgeonName){}

Inheritance-
In our project for common functionality we created one class and implemented all methods.
And whenever we required that functionality we inherited that class and if any changes
required in any method we override that method as per requirement.
Eg. In our project we generated multiple reports. To Fill all dropdowns in report generation
section we implemented all methods in one class and inherited that class.

Encapsulation and abstraction-


We implemented all methods private which are required for only that class. Some method
we called through ajax call so we have to implement that with public access specifier.

Q. Have you used delegates if used then how and where you used in your project?
Say I know delegates but not used in our project.

Q. Where you have used anonymous methods in your project?


Yes. We used anonymous method in jquery to execute the jquery code on page load

Q. Where you have used extension methods in your project?


Not used in project.

Or

We created extension method to create the html helper for button.

Q. Have you used reflection then how and when you used it in your project?
Not used in project.

Q. How you handled exceptions in your project?


Q. Or which exceptions handling you did in your project?
Q. Or how you handled errors in your project?
Q. How you logged the application level errors?
We used handle error attribute in some cases to handle the exception. To handle application
level events we implemented the Application_Error method which are present in Global.asax
page. And we logged that errors in database and text file.

Q. Have you used scaffolding in your project?


No.

Q. Where you have used data annotations in your project?


Yes we used data annotations in our project. For fields like email, username, password
Eg.
public class ChangePasswordBindingModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }

[Required]
[StringLength(10, ErrorMessage = "The {0} must be at least {2} characters long.",
MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }

[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation
password do not match.")]
public string ConfirmPassword { get; set; }
}

Q. Which authentication you used in your project?


In our all projects we used form authentication. In some projects we authenticate username
and password in our database.

Q. How you secured the web api?


In our project, we have 2 differernt servers. One server is internal server on which we have
hosted our api and another server is MVC server we call it as dmzServer(demontized server)
which is outside server. So we have used CORS to authenticate user. And at MVC side we
have used OCTA tool to authenticate user.. which was provided by client so when user enter
credentials it will redirect to OCTA tool so after authenticating user can login into UI layer.

Q. Which filters you have used in your project?


We implemented the Authorization filter in our project. We inherited the
AuthorizationFilterAttribute class and override the OnAuthorization method. We used that
filter to authorise the user while login to the application.

Q. Have you used caching in your project? Which type of cache used?
No.

Q. Where you used jquery in your project?


In my all projects there is one portal. On portal to do all client side operation like auto
dropdown fill, to give pop ups, messages, warning we used jquery
Q. Where you have used ajax?
In my our project to consume WebApI we have create ajax call.

Q. Have you implemented normalization in your project?


Yes. I created multiple tables and given the relationship using primary- foreign key

Q. Which index you created in your project?


No. But we created clustered index by creating primary key on tables.

Q. Do you used joins in entity framework?


Yes. I used joins in entity framework to get data from multiple tables.

Q. Are you direct payroll of company?


Yes I am.

Q. Who is CEO of your company?


CEO name is Somnath Zadbuke. And HR executive Rohini Z.

Q. How many employees are there in your organization?


around 250 employees are there in our company.

Q. Where is your office located? Or where you actually worked tell me address?
OppAndhara Bank, Sahawas Road, Karve Nagar, Pune -52

Q. What do you know about our company?


(Please read about basic info about company where you are going for interview- MNC or
not, company's client, projects domain )

Q. What is hierarchy in your organization? Draw it on page


Eg.1.

Eg.2
Q. Tell me your manager name?
me?
My manager name is Subodh pad
padgilwar, My Team lead name is Laxmikanthemke

Q. How you communicate with ith testers?


t Tell me in details how testers log the defe
efect and
how you start working on itt and how you update them about status?
In my company After developmepment we give our application to tester with all details.
ails. Then
tester test and find the bugs,, ass
assign a task to respective Developer. After fixing the
he b
bug we
mark as completed in office task
task.

Q. Why you are leaving yourr cur


current organization? Or
Q. Why are looking for job chan
hange?
Because my current project is sta
stable. I don’t have any dependencies. And moreover
ver, to
enhance my skillset, I am looking
king for better opportunity to grow myself professional
onally.

Q. In your organization you are not


n getting any career growth?
No, I am getting much exposure
ure there but I want to grow in another organization
n as well.

Q. Why should I hire you? or


In my best capacity, I rea
really think that I can be the perfect fit for this job because
bec I
hold every expertise and every ry sk
skill required for this job description. And I wouldd ensure
en that
I will put my best efforts to grow
row my career and your business.

Q. Tell me about your strengths


gths.
About my strength, I am flexible
ible and adoptable towards my work and enthusiasm
m to learn
new things.

Q. Tell me about your weakness


nesses.
About my weakness, Shynesss wa
was the one I faced earlier and now I was able to over
vercome it
with confidence and passion tow
towards work.

Q. How long would you expect ect to


t wok for us if I hired you?
I haven’t think about that , I am just
j focusing to get this job. But, yes I will work as lo
long as my
presence benefit the company. ny.

Q. What are your goals?


My short term goal is to be part of this company. And understand my roles and
responsibilities and to work according to company work culture. And my long term goal is to
be a team leader.

Q. What are your outside interests?


My outside interests are listening music, playing cricket, travelling to new places and hanging
out with friends.
Q. Tell me 3 negative aspects about your team lead.
I don’t see any kind of negative aspects in our team lead but there are some improvement
areas. Actually he is workaholic (works excessively hard and long hours). He expects much
things from us but actually we are trying our best to do much things as per the company
policy.

Q. Tell me 3 negative aspects about your company.


Actually none of the company is best or perfect still there are some improvement areas. I
don’t see any kind of negative aspects in my current organization. As per I am leaving the
organization I learned lots of things from my company now I want to apply these in another
organization and maybe I get some more exposure in another company.

Q. What is your notice period?


Its 1 month(or it may different)

Q. Is it negotiable?
Yes. It is negotiable.

Q. How it is negotiable? Or how you join within 1 month?


I already had offline discussion with my manager and he is ready to leave me as early as
possible if I get good opportunity outside.

Q. What if your company hire you on his own payroll?


I don't think so
I am working with my organisation since last 4 years
Until they didn't done that
I don't think they do that now
And if they do
It's been long duration I am working with same work culture
Now I want work in different work culture of different company so I can get more exposure

Q. if Question on pf and salary-


I don't have any pf. My employer does not provide me any pf
My salary is fixed.No variable amount.

Q. How soon can you join?


I try my best to join as soon as possible. Let me discus with my HR.

Q. What is your current CTC?


My current CTC is 6.5 lakhs. (it may vary)

Q. What is your expected CTC?


My expected CTC is 8.5 lakhs/(if CTC- 6.5) I want at least 30 percent hike on my current CTC.

Q. Is it negotiable?
Yes it is negotiable.
Q. Do you have any questions to ask?
Like u know , just wanted to understand what kind of requirement you are recruiting for i.e.
to develop the product starting from scratch or its existing prduct where we are going to
enhance modules like that.
JavaScript Interview Questions
1. What is JavaScript ? or JavaScript is which type of Language ?
 It is object-based scripting language.
 It is widely used for client side validation.

2. Why we use JavaScript ?


 Using Html we can only design a web page but cannot run any logic on
web browser like addition of two numbers, check any condition, looping
statements(for, while), decision making statement(if-else) etc at client
side, so for perform all these task at client side we use JavaScript.

3. Is JavaScript case sensitive ?


 Yes

4. Where JavaScript is used ?


 It is used to create interactive websites.
 It is mainly used for:
 Client-side validation
 Dynamic drop-down menus
 Displaying data and time
 Build small but complete client side programs
 Displaying popup windows and dialog boxes (like alert dialog box,
confirm dialog box and prompt dialog box)
 Displaying clocks etc.

5. How do we add JavaScript onto a web page?


 Between <body><body/> tag of html using <script><script/> tag.
 Between <head><head/> tag of html using <script><script/> tag.
 Add in .js file and refer url whenever required. (External JavaScript)

6. What is the difference between == and === ?


 The == sign checks only value equality whereas === sign checks for type
and value equality.

Ex. var i = 10;


var j = “10”;

var a = (i == j) ; ---> True

var b = (i === j) ; ---> False

7. How to declare variable in JavaScript ?


 We can use var keyword to declare variables in JavaScript.
 Because JavaScript did not provide any data types for declaring variables.
8. What would be the difference if we declare two variables inside a
JavaScript, one with 'var' keyword and another without 'var' keyword ?
 The variable with var keyword inside a function is treated as Local variable
whereas the variable without var keyword inside a function is treated a global
variable.

9. What is function hoisting in JavaScript?


 By default, JavaScript moves all the function declarations to the top of the
current scope is called function hoisting.

10. How to write function in JavaScript?


function Add(a,b)
{
document.write(a + b);
}

Add(10,10);

11. How to write anonymous function in JavaScript?


var Add = function(a,b)
{
document.write(a + b);
}

Add(10,10);

12. What is Self-Invoked function or Imediately-Invoked Function


Expression(IIFE) in JavaScript ?
 This function invoked automatically without being called.

(function(a, b)
{
document.write(a + b);
})(10,10);

13. What is a closure in JavaScript ?


 JavaScript allows you to declare a function inside function and inner function has
access of outer function variables and outer function parameter called closure.

function Add(a, b)
{
var result = “Addition = “;

function add()
{
document.write(result + (a + b));
};

add();
};
14. How to access the value of a textbox using JavaScript ?
 Using var tb = getElementById(“”).value

15. How to create arrays in JavaScript ?


 var array = new Array(2); // 2 is size of array and it automatically grows
 var array = new Array(10,20); // we can also pass arguments in array
 var array = [10,20,30,40];

16. What are the Array Mutators ?


 The methods that modify the array objects are called a mutator methods.
1) push() :
push() method adds new item to the end of array.
2) pop() :
pop() method removes the last item of an array.
3) unshift() :
unshift() method adds new item at the beginning of an array.
4) shift() :
shift() method removes first item of an array.
5) reverse() :
reverse() method reverse the sequence of an array elements.
6) sort() :
sort() method sorts the elements of an array.
sort() method works well for string not for integers, we can fix this by
providing a compare function.
7) splice() :
splice() method used to remove and add elements in array on index basis.

17. What is event bubbling in JavaScript ?


 With event bubbling the event bubbles up (i.e. triggers) from inner most
element to outer most element in the DOM hierarchy.

18. What is event capturing in JavaScript ?


 With event capturing the event captured (i.e. triggers) from outer most element
to inner most element in the DOM hierarchy.

19. How to prevent browser default action ?


 When we click on link it will redirect to link url.
 When we right click it gives context menu.
 To prevent these type browser action we use

onContextMenu = “return false”

20. What does the isNaN() function ?


 The isNan() function returns Boolean as output when we check for variable is a
number or not.

21. How can you submit a form using JavaScript?


 To submit a form using JavaScript use document.form[0].submit();
22. What is SubStrings in JavaScript ?
1) substring():
 This method has 2 parameters Number start and Number end.
 Start parameter is required and specifies the position where to start the
extraction.
 End parameter is optional and specifies the position where the extraction end.
 When end parameter not specified then all the characters from the start
position to end of the string are extracted.
 If value of start parameter is greater than end parameter then it swaps the two
arguments.
2) slice() :
 Same as substring() method but does not swaps arguments.
3) substr() :
 This method has 2 parameters Number start and Number length.
 Start parameter is required and specifies the position where to start the
extraction.
 Length parameter is optional and specifies the length where the extraction end.
 If value of start parameter is greater than end parameter then it does not swaps
the two arguments.

23. What is JavaScript argument object ?


 The javascript argument object is a local variable which is available within all
functions.
 With argument object we can access function parameters passed to function like
an array.
 The length property of the arguments object returns the number of arguments
passed to function.

24. What are JavaScript timing events ?


1) setInterval(func,delay) :
Executes a specified function repeatedly at specified time interval.

2) setTimeout(func,delay) :
Executes a specified function after waiting a specified number of
milliseconds.

3) clearInterval(intervalID):
Cancels the repeated execution of the method that was setup using
setInterval() method.

25. Does JavaScript support automatic type conversion?


 Yes JavaScript does support automatic type conversion, it is the common way of
type conversion used by JavaScript developers.

26. What are all the looping structures in JavaScript?


 While
 Do-While
 For
27. What are the Mouse events in JavaScript ?
 An event is signal from browser that something has happened.
1) mouseover : Occurs when the mouse pointer is moved over an element.
2) mouseout : Occurs when the mouse pointer is moved out of an element.
3) mousemove : Occurs when the mouse pointer is moving over an element.
4) mouseup : Occurs when the mouse button is released over an element.
5) mousedown : Occurs when the mouse button is pressed over an element.
6) click :Occurs when the mouse button is clicked.
7) dblclick :Occurs when the mouse button is double clicked.
8) contextmenu :Occurs when the mouse right button is clicked.

28. What are the regular expressions in JavaScript ?


 Regular expression is a sequence of characters that forms a search pattern.
1) match() : All numbers in string will be returned.
2) replace() : All numbers will be replaced with given parameter.
3) split() : Breaks a string into an array of substring.
4) search() : Returns the index of the first matching item only.

29. What is JavaScript Minification ?


 Javascript minification is the process of reducing the script file by removing
comments, extra white spaces and new line characters that are not needed for
executing javascript code.
 The javascript minification may reduce the size of the file by 30 to 90%.
 The minification process will not change its original functionality.
Advantages :
 Reduce download time of javascript file on client machine before browser can
execute your js code.
 Multiple javascript files can be compressed into one minified js file.
Dis-Advantages :
 Readability is lost.

30. What are all the types of Pop up boxes available in JavaScript?
 Alert - Alert box displays only one button which is the OK button.
 Confirm - Confirmation box displays two buttons namely OK and cancel.
 Prompt

31. How to handle exceptions in JavaScript?


 By using try-catch blocks
32. What are the different types of errors in JavaScript?
 There are three types of errors:
1) Load time errors:
Errors which come up when loading a web page like improper syntax errors are
known as Load time errors and it generates the errors dynamically.

2) Run time errors:


Errors that come due to misuse of the command inside the HTML language.

3) Logical Errors:
These are the errors that occur due to the bad logic performed on a function
which is having different operation.

You might also like