C# ADO EF LINQ DB MVC Jquery
C# ADO EF LINQ DB MVC Jquery
C# ADO EF LINQ DB MVC Jquery
Sealed class is used to prevent the class from being inherited from other classes.
So “sealed” modifier also can be used with methods to avoid the methods to
override in the child classes.
Dispose - This method uses interface – “IDisposable” interface and it will free up
both managed and unmanaged codes like – database connection, files etc.
Finalize - This method is called internally unlike Dispose method which is called
explicitly. It is called by garbage collector and can’t be called from the code.
6. What is the difference between “throw ex” and “throw” methods in C#?
“throw ex” will replace the stack trace of the exception with stack trace info of re
throw point.
Managed Code
“The code, which is developed in .NET framework is known as managed code. This code
is directly executed by CLR with the help of managed code execution. Any language that
is written in .NET Framework is managed code”.
Unmanaged Code
The code, which is developed outside .NET framework is known as unmanaged code.
Ensures a class has only one instance and provides a global point of access to it.
10. Can you change the value of a variable while debugging a C# application?
Yes, if you are debugging via Visual Studio.NET, just go to Immediate window.
11. Difference between Equality Operator (==) and Equals() Method in C#.
Answer:
Both the == Operator and the Equals() method are used to compare two value type data
items or reference type data items.
The Equality Operator (==) is the comparison operator and the Equals() method
compares the contents of a string.
The == Operator compares the reference identity while the Equals() method compares
only contents. Let’s see with some examples.
Access modifiers are an integral part of object-oriented programming. They support the
concept of encapsulation, which promotes the idea of hiding functionality. Access
modifiers allow you to define who does or doesn't have access to certain features.
Answer :
N
Data Reader DataSet
o
1 Used in a connected architecture Used in a disconnected architecture.
2 Provides better performance Provides lower performance.
3 DataReader object has read-only access A DataSet object has read/write access
DataReader object supports a single table A DataSet object supports multiple tables
4
based on a single SQL query of one database from various databases.
A DataReader object is bound to a single A DataSet object is bound to multiple
5
control. controls.
6 A DataReader object has faster access to data. A DataSet object has slower access to data.
A DataReader object must be manually A DataSet object is supported by Visual
7
coded. Studio tools.
8 We can't create a relation in a data reader. We can create relations in a dataset.
Whereas a DataReader doesn't support data A Dataset supports integration with XML
9 reader communicates with the command Dataset communicates with the Data Adapter
object. only.
10 DataReader cannot modify data. A DataSet can modify data.
2. Difference between
ExecuteScalar
ExecuteNonQuery
ExecuteReader
ExecuteScalar is useful for returning a single value from the database. For example, using this
method we can retrieve a sum of sales made by a specific product, total number of records in
the employee table, unique id by supplying filtering conditions and so on. Since this method
performs faster we do not need to go for the Reader method just to retrieve a single scalar
value.
ExecuteNonQuery is useful for performing data manipulation on the database. Simply, the
ExecuteNonQuery is for executing the DML statements. The return value of the
ExecuteNonQuery is an integral value that represents the number of rows affected by the
Operation.
ExecuteReader is used when we need to retrieve rows and columns of data using the SQL
select statements. As the data retrieved is a table of data, ExecuteReader returns SqlDataReader.
We should iterate through this object to get the required values.
3. How to copy one dataset data?
dataGridView2.DataSource = daset.Tables[0];
4. What does the parameter Initial Catalog define inside Connection String?
6. Write sample code to open sql connection to read data from Customer table(SQL
database).Customer_Id is the first column of the table.Print customer ids at console
one at time.
try
{
// 2. Open the connection
conn.Open();
MVC
1. What is MVC?
Ans:
Model: Model represents the application data domain. In short the applications business
logic is contained within the model.
View: Views represent the user interface, with which the end users interact. In short the
all the user interface logic is contained within the UI.
Controller: Controller is the component that responds to user actions. Based on the user
actions, the respective controller, work with the model, and selects a view to render that
displays the user interface. The user input logic is contained within the controller.
Authorization Filters - The ASP.NET MVC Authorize filter attribute implements the
IAuthorizationFilter interface. The definition of this interface is given below-
Action Filters - Action filters are executed before or after an action is executed. The
IActionFilter interface is used to create an Action Filter which provides two methods
OnActionExecuting and OnActionExecuted which will be executed before or after an
action is executed respectively.
Result Filters - Result filters are executed before or after generating the result for an
action. The Action Result type can be ViewResult, PartialViewResult,
RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult and
EmptyResult which derives from the ActionResult class. Result filters are called after the
Action filters. The IResultFilter interface is used to create a Result Filter which provides
two methods OnResultExecuting and OnResultExecuted which will be executed before or
after generating the result for an action respectively.
Exception Filters - Exception filters are executed when exception occurs during the
actions execution or filters execution. The IExceptionFilter interface is used to create an
Exception Filter which provides OnException method which will be executed when
exception occurs during the actions execution or filters execution
Ans. You can enable and disable optimizations by setting Enable Optimizations property
of Bundle Table class to true or false with in Global.asax.cs file as shown below. protected
void Application_Start()
{
//other code has been removed for clarity
//disable optimization
System.Web.Optimization.BundleTable.EnableOptimizations = false;
}
2nd Way
protected void Application_Start()
{
//Enable or Disable Client Side Validation at Application Level
HtmlHelper.ClientValidationEnabled = true;
HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
}
3rd Way
@using MvcApp.Models
@{
ViewBag.Title = "About";
HtmlHelper.ClientValidationEnabled = false;
}
10. What is Area in ASP.NET MVC?
Ans. Areas was introduced in Asp.net MVC2 which allow us to organize models, views,
and controllers into separate functional sections of the application, such as
administration, billing, customer support, and so on. This is very helpful in a large web
application, where all the controllers, views, and models have a single set of folders and
that become difficult to manage.
11. What is output caching?
Ans. The OutputCache filter allow you to cache the data that is output of an action method.
By default, this attribute filter cache the data till 60 seconds. After 60 sec, ASP.NET MVC will
execute the action method again and cache the output again.
ViewBag.Message = DateTime.Now.ToString();
return View();
=========================================================
===============
Entity Framework
1. What is Entity Framework?
Entity Data Model or EDM refers to a set of concepts that describe data structure,
regardless of its stored form. It is a bridge between application and data storage and
helps us to work at a conceptual level rather than the actual schema. It uses three key
concepts to describe data structure (entity type, association type and property).
An .edmx file (Entity Data Model XML) is an XML file. It defines a conceptual model, a
storage model, and the mapping between these models. This file also contains the
information that is used by the ADO.NET Entity Data Model Designer to render a model
graphically. It contains all the mapping details of how objects map with SQL tables. It is
divided into three sections: CSDL, SSDL, and MSL.
Eager loading
Lazy loading
Explicit loading
6. What is Lazy Loading?
Lazy loading is the process to delay the loading of related objects until we need it. Other
hand, on demand objects loading rather than loading objects unnecessarily. When
objects are returned by a query related objects are not loaded at the same time.
[ Fist query will load main object and the related objects will be loaded in second
queries.]
The opposite of Lazy Loading is eager loading. Eager loading is the process of loading
related entities/ objects.
If lazy loading disabled it is still possible to lazily load related entities. For this we need to
call the Load method on the related entities.
The Entity Framework supports three different development approaches to use entity
framework in our applications.
Code First
Model First
Database First
Code First
If we have existing application with domain classes Want to create database from your
existing domain classes
Model First
If we have existing database
Database First
If we don’t have existing database or domain classes, and we prefer to design our db
model on the visual designer
LINQ
1. Explain what is LINQ? Why is it required?
Language Integrated Query or LINQ is the collection of standard query operators which
provides query facilities into.NET framework language like C#, VB.NET.
LINQ is required as it bridges the gap between the world of data and world of objects.
LINQ to Objects
LINQ to XML
LINQ to Dataset
LINQ to SQL
LINQ to Entities
5. Explain what is the difference between Skip() and SkipWhile() extension method?
Skip() : It will take an integer argument and from the given IEnumerable it skips the top n
numbers
SkipWhile (): It will continue to skip the elements as far as the input condition is true. It
will return all remaining elements if the condition is false
Web API
1. What is Web API?
It is a framework which helps us to build/develop HTTP services. So there will a client
server communication using HTTP protocol.
2. What is Representational state transfer or REST?
REST is architectural style, which has defined guidelines for creating services which are
scalable. REST used with HTTP protocol using its verbs GET, POST, PUT and DELETE.
3. What are the advantages of using REST in Web API?
REST always used to make less data transfers between client and server which makes
REST an ideal for using it in mobile apps. Web API supports HTTP protocol thereby it
reintroduces the old way of HTTP verbs for communication.
4. Difference between WCF Rest and Web API?
WCF Rest
“WebHttpBinding” to be enabled for WCF Rest.
For each method there has to be attributes like – “WebGet” and “WebInvoke”
For GET and POST verbs respectively.
Web API
Unlike WCF Rest we can use full features of HTTP in Web API.
Web API can be hosted in IIS or in application.
5. List out differences between MVC and Web API?
MVC
MVC is used to create a web app, in which we can build web pages.
For JSON it will return JSONResult from action method.
All requests are mapped to the respective action methods.
Web API
This is used to create a service using HTTP verbs.
This returns XML or JSON to client.
All requests are mapped to actions using HTTP verbs.
6. What are the advantages of Web API?
Below are the list of support given by Web API –
OData
Filters
Content Negotiation
Self Hosting
Routing
Model Bindings
7. How to unit test Web API?
We can unit test the Web API using Fiddler tool. Below are the settings to be done in
Fiddler
Compose Tab -> Enter Request Headers -> Enter the Request Body and execute
8. List out the steps to be made for Web API to work in Web Forms?
Below are the steps to be followed –
Creating new controller for Web API.
Adding routing table to “Application_Start” method in Global.asax
Make a AJAX call to Web API actions.
9. What is “Under-Posting” and “Over-Posting” in Web API?
“Under-Posting” - When client leaves out some of the properties while binding
then it’s called under – posting.
“Over-Posting” – If the client sends more data than expected in binding then it’s
called over-posting.
10. How to handle validation errors in Web API?
Web API will not return error to client automatically on validation failure. So its
controller’s duty to check the model state and response to that. We can create a custom
action filter for handling the same.
11. Can you restrict a WEB API action method to be invoked only by HTTP GET, POST,
PUT or DELETE?
Ans. Like ASP.NET MVC, you can also restrict WEB API action method to be invoked only
by a specific HTTP request by applying HttpGet or HttpPost or HttpPut or HttpDelete
attribute.
If you want to restrict an action method for HTTP Get request only then decorate it with
HttpGet action method selector attribute as given below:
[HttpGet]
public IEnumerable<Product> ProductList()
{
return db.Products.AsEnumerable();
}
Jquery
Ans: The starting point of jQuery code execution is $(document).ready() function which is
executed when DOM is loaded.
Ans: Dollar Sign is nothing but it's an alias for JQuery. Take a look at below jQuery code.
Hide Copy Code
$(document).ready(function(){
});
Ans: YES. We can have any number of document.ready() function on the same page.
4. What is jQuery.noConflict?
Ans: As other client side libraries like MooTools, Prototype can be used with jQuery and they
also use $() as their global function and to define variables. This situation creates conflict as $() is
used by jQuery and other library as their global function. To overcome from such situations,
jQuery has introduced jQuery.noConflict().
Hide Copy Code
jQuery.noConflict();
// Use jQuery via jQuery(...)
jQuery(document).ready(function(){
jQuery("div").hide();
});
Ans: jQuery library comes in 2 different versions Development and Production/Deployment. The
deployment version is also known as minified version. So .min.js is basically the minified version
of jQuery library file. Both the files are same as far as functionality is concerned. but .min.js is
quite small in size so it loads quickly and saves bandwidth.
Database
1. Assuming you have a table with Employee Name and its manager ID, how do you
write report to show this data hierarchically? I want employee name and his
manager name.?
Lets assume we have following table structure and It contains employee manager
relationship data,
CREATE TABLE tbEmployee
(
EmployeeId INT PRIMARY KEY,
EmployeeName VARCHAR(50),
ManagerId INT
)
And it contains following data
INSERT tbEmployee
VALUES
(25,'Salman',NULL),
(26,'Ranbeer', 25),
(27,'Hrithik',25),
(28,'Aamir',27),
(29,'Shahid',28),
(30,'Sidharth', NULL),
(31,'Varun', 30),
(32,'Kabeer', 30),
(33,'Raj', 29);
Result:
EmployeeId EmployeeName ManagerId
25 Salman NULL
26 Ranbeer 25
27 Hrithik 25
28 Aamir 27
29 Shahid 28
30 Sidharth NULL
31 Varun 30
32 Kabeer 30
33 Raj 29
Now write a query for employee and manager relationship hierarchy with level.
Answer
CTE recursive query to get employee and manager relationship hierarchy with level.
;WITH EMP_CTE AS
(
SELECT EmployeeId, EmployeeName, ManagerId, CAST('' AS VARCHAR(50)) ManagerNam
e, 0 AS EmployeeLevelFROM tbEmployee WHERE ManagerId IS NULL
UNION ALL
SELECT T.EmployeeId,T.EmployeeName, T.ManagerId,CAST(C.EmployeeName AS VARCHA
R(50)) ManagerName,EmployeeLevel + 1 AS EmployeeLevel FROM tbEmployee AS T
INNER JOIN EMP_CTE AS C ON C.EmployeeId=T.ManagerId
)
SELECT * FROM EMP_CTE
Result:
EmloyeeId EmployeeName ManagerId ManagerName EmployeeLevel
25 Salman NULL 0
30 Sidharth NULL 0
31 Varun 30 Sidharth 1
32 Kabeer 30 Sidharth 1
26 Ranbeer 25 Salman 1
27 Hrithik 25 Salman 1
28 Aamir 27 Hrithik 2
29 Shahid 28 Aamir 3
33 Raj 29 Shahid 4
Explanation: The base record for the CTE is obtained by the first select query above UNION ALL.
It gets all EmployeeId which don’t have ManagerId ie. NULL value. This means they are the top
most employees of the organization so their Employee Level is set to 0.
Second select query below UNION ALL is executed recursively to get results and it will continue
until it returns no rows. E.g. Result will have EmployeeIds which have ManagerId (i.e, EmployeeId
of the first result). This is obtained by joining our CTE result with tbEmployee table on columns
EmployeeId of CTE with ManagerId of table tbEmployee.
This process is recursive and will continue till there is no ManagerId who doesn’t have
EmployeeId.
BEGIN TRANSACTION;
DELETE FROM HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT;
Table A
1 A
2 B
3 C
4 D
Table B
3 C
4 D
5 E
6 F
7 G
8 H
9 I
10 J
11 K
12 L
8. How to find last inserted record id in current scope in sql server? (Scope_Identity())
9. Explain function :
ROW_NUMBER
RANK
Ans : - ROW_NUMBER and RANK are similar. ROW_NUMBER numbers all rows
sequentially (for example 1, 2, 3, 4, 5). RANK provides the same numeric value for ties
(for example 1, 2, 2, 4, 5).
Documentation :
1. What type of documentation you have created ?
1)DDD
2)FSD
3)TSD
4)Test Cases
5)Code Review Document