All Qa-1
All Qa-1
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.
4. What is chaining?
Chaining are used to run multiple jQuery methods (on the same element) within a single
statement.
- With MVC 5 there are many important features were introduced. Support for Bootstrap, Attribute
based routing, ASP.NET identity support.
- 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.]
- 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.
- Yes we can define such routing. But we need to take care for url request.
- 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.
- http://www.dotnettricks.com/learn/mvc/custom-authentication-and-authorization-in-aspnet-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.
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.
- We can use Query string, Hidden fields or form posted values to transfer data from view to
controller.
- 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.
- Yes we can pass data from Controller to View using Tempdata. We can access Tempdata object in
View.
- 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.
- 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.
- 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]
- 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.
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.
- We can use MapRoute method and configure more than one routes. We have to mandatory
provide name and url parameters to MapRoute method.
- 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.
- 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.]
- 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.
- Filters are use to execute logic before and after execution of an action method. Filters are broadly
categorized in 4 categories –
- 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(){}
});
- 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.
- 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.
- In client side state management techniques we have Query string, Hidden field, Cookies.
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 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.
- 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.
- 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.
- 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.
- Already done.
- 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.
- 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/]
- 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.
- 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.
- To maintain session we have used ViewBag, ViewData, TempData, Session variables. Depending on
scope we have used these options one over another.
- 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.
});
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.
- 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.
- 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.
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.
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.
- 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.
- Refer Question 9.
- 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.
- Refer Question 2.
- 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.
- 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 view can have two submit buttons. On clicking on those submit button respective action
methods are called which are defined with form tag.
- 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.
- We do all validations in models using validation attributes. All validation specific attributes are
define in System.ComponentModel.DataAnnotations.
- 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.
- Yes we have used cookies to store some non-critical data of user which we had to use in multiple
pages.
- 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?
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.
- We can AJAX to call action method without refreshing a page. Refer Question 30.
- 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.
- 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.
- 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
- 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.
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.
- 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.
- 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.
- 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.
- 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?
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.
- 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.
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.]
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.
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.
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]
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 :
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.
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 :
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.
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.
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.
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.]
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:
- 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.
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.
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 :
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.
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.
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.
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.
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.
Row_Number function
Rank function
Dense_Rank function
45. How to find nth highest salary from employees table (explain different ways).
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.
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.
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
[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 :
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
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
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.
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.
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:
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:
() => 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.
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.
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:
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.
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.
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.
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 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.
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.
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.
--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
on delete no action
on delete cascade
on delete set null
on delete set default
--------------
--Identity column
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
------------
--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:
-----------------
==Union and union all in sql server
-- union all,union,intersect,except
----------------
==Subqueries
--subquery used in where clause
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.
sp_depends {SP_Name}
----------------------
--------------------------------------
==Built in string functions in SQL
--while loop
Declare @Number int
Set @Number = 65
While (@Number <= 95)
Begin
Print char(@Number)
Set @Number = @Number + 1
End
DATATYPES
DATE,TIME,SMALLDATETIME,DATETIME,DATETIME2,DATETIMEOFFSET
----------------
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 ] )
--------------------
---------------
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 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 )
Syntax :
DATETIMEOFFSETFROMPARTS ( year, month, day, hour, minute, seconds, fractions,
hour_offset, minute_offset, precision )
---------------------------------------------------
--parameterized scalar fn
-----------------
--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)
Return
End
--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.
--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
--6. Create a new table whose columns and datatypes match with an existing table.
--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
--To delete or drop the index: When dropping an index, specify the table name as well
Drop Index tblEmployee.IX_tblEmployee_Salary
----------------------------------
==Views in sql server
--DDL triggers scope : DDL triggers can be created in a specific database or at the server level.
--Logon trigger example : The following trigger limits the maximum number of open
connections for a user to 3.
----------------
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
open employeeCursor
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 )
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, ...)
------------------------------------------------
==Pivot operator in sql server
-------------------------------
--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
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 ?
• This Main() method is an entry point where program starts its execution.
• As C# is a case sensitive language it means Main(), main(), MAIN() these method names
are treated as different.
• 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.
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 ?
• Type casting.
float a = 10;
int b = (int) a;
float a = 10;
int b = Convert.ToInt32(a);
• Using as Keyword.
We can use Parse and TryParse methods when we need to convert a string to other
types like int, bool, float etc.
• Cast operator handles the exceptions whereas Convert class does not handle and throws
the exceptions like Overflow Exception, Format Exception etc.
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
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.
• 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.
• 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.
• 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 –
• They are extensively used in LINQ expressions whenever you want to return only a few
properties from its properties.
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
• 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
• You can assign value to dynamic and also can change value type stored in same.
• 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
• Looping is a way to execute block of code multiple times depending upon condition.
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
• Value type does not hold null values but it can achieved using nullable type.
int? i = null;
(for example, in SQL int type can hold null values and in C# by default int is non nullable.)
If we want to convert from a nullable type to non-nullable type then we can Null
coalescing operator.
• 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.
• 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
• 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.
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.
Output Parameters
• Any parameter value changes in called method will reflect in calling 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?
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
Optional Attribute
Data Members
Member Function
Any method or function inside a class is nothing but the member function.
• There are different types of constructors we can write inside a class like
• Static constructors are called only once regardless of how many instances of the class
are created.
• 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.
• 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 extensibility it means we can easily plug a new type without
affecting the existing functionalities.
2) Runtime Polymorphism
– Method Overriding
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?
• 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.
• 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.
• Compiler does not find any difference in normal array parameter and a parameter array
at compile time.
• 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.
• Method overloading and method overriding both are the types of polymorphism.
• 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?
• 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.
• Indexers are used to design our indexed based class objects just like an array.
• In real time, Session object, Data Table object, Rows Object uses indexers to access the
values.
• 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.
• If we talk in terms of coding perspective, public fields shows abstraction and private
fields shows encapsulation.
• 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.
• 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.
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.
• This implemented methods by default public. We cannot specify any other access
modifier even a public.
• Creating a class object and then type casting as interface and invoking a method.
40. What are abstract classes ? Can it be instantiated?
• They are just like concrete classes but they contain both abstract and non-abstract
members.
• Object of abstract class is not possible but an abstract class reference variable can point
to a derived class object.
41. Can abstract class have a constructor? When it will get called?
• Abstract class constructors get called before derived class constructor call.
• Sealed class are prevented from inheritance it means Sealed classes cannot be used as
base 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.
• 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.]
46. What is default access specifier for type and type members?
• Internal access modifiers are accessible from anywhere within the same assembly. We
cannot access them outside assembly.
• When the application is compiled, all these parts then combined into a single class.
Rules :
• 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 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 return type must be void. Giving any other type gives compile time error.
• 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.
• 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.
• So we can use finally block to close the open connection or if we want to explicitly free
the resources.
55. Can we customize values in enum? What is default start value to enum?
56. What is default underlying type to enum? Can we change its underlying type to some
other type?
• 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
1) GetType()
2) ToString()
3) Equals()
4) GetHashCode()
• 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.
• 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.
• 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.
• But when we use == operators with complex types it just check reference equality and
not value equality.
Static
Static fields have a single copy regardless of how many instances of the class are created.
Constant
Readonly –
• Readonly fields are also similar to constant variables but we can change its value at
runtime through non static constructors.
• We can also have static readonly fields in which we can assign value at runtime through
static constructor but only once.
• Delegates signature should get match with method signature that’s why it is called as
type safe.
67. What are types of delegates? Predicate, Action and Func Delegate?
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.
• 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.
• 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.
• 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.
• Generic collections are type safe because there is no boxing and unboxing operations
which actually helps to improve system performance.
Anonymous methods :
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.
75. What is lambda expression? Interviewer can ask to write a small program using
lambda expressions.
• 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.
• 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 use IEnumerable for in memory collection like List, Dictionary whereas we use
IQuerable for remote servers like SQL server.
• 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.
• 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.
classSingleton
{
privatestaticSingleton _instance;
private Singleton()
{
}
publicstaticSingleton Instance()
{
if (_instance == null)
{
_instance = newSingleton();
}
return _instance;
}
}
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.
• 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.
Association
• Inheritance defines the ‘is a’ relationship just like Association defines ‘has a’relationships
between objects.
Aggregation
• 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
• 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
Founder :Shivkumar
Email : [email protected]
Mobile. 8956890522
HR Manager :Shivkumar
Email: [email protected]
Mobile: 9890055031
***************************************
Project Handled:
Print Shoppy
Move Goods
Library
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
Email: [email protected]
Mobile :9730225992
Email: [email protected]
***************************************
Questions:
1. Are you on permanent payroll or are you permanent employee?
- yes I am on permanent payroll for this company.
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.
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.
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.
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.)
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.)
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 )
***************************************
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.
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))
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.
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.
- this is the amount from our package which we don’t get every month.
20. UAN?
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 ->
ID card
Access Card -> using this card you can access to office premises
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
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.
Around 35 to 40 tables
Ex. rsm_Role, rsm_User, rsm_Admin, rsm_Order, rsm_VehicleType, rsm_VehicleOwner,
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. 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.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
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.
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.
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.
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.
Or
Q. Have you used reflection then how and when you used it in your project?
Not used in project.
[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. Have you used caching in your project? Which type of cache used?
No.
Q. Where is your office located? Or where you actually worked tell me address?
OppAndhara Bank, Sahawas Road, Karve Nagar, Pune -52
Eg.2
Q. Tell me your manager name?
me?
My manager name is Subodh pad
padgilwar, My Team lead name is Laxmikanthemke
Q. Is it negotiable?
Yes. It is negotiable.
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.
Add(10,10);
Add(10,10);
(function(a, b)
{
document.write(a + b);
})(10,10);
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
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.
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
3) Logical Errors:
These are the errors that occur due to the bad logic performed on a function
which is having different operation.