C# ADO EF LINQ DB MVC Jquery

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

C#

1. Explain the types of comments in C#?

Below are the types of comments in C# -

 Single Line Comment Eg : //


 Multiline Comments Eg: /* */
 XML Comments Eg : ///

2. Explain sealed class in C#?

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.

3. Why to use “using” in C#?

“Using” statement calls – “dispose” method internally, whenever any exception


occurred in any method call and in “Using” statement objects are read only and
cannot be reassignable or modifiable.

4. What is the difference between “dispose” and “finalize” variables in C#?

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.

5. What is the difference between “finalize” and “finally” methods in C#?

Finalize – This method is used for garbage collection. So before destroying an


object this method is called as part of clean up activity.

Finally is use in exception handling. And it gets executed every time.

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.

“throw” will preserve the original stack trace info.

7. What is Managed or Unmanaged Code?

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.

8. What is the difference between constant and read only in c#?

Constant (const) and Readonly (readonly) both looks like same as per the uses


but they have some differences: 

Constant is known as “const” keyword in C# which is also known immutable


values which are known at compile time and do not change their values at run
time like in any function or constructor for the life of application till the
application is running.

Readonly is known as “readonly” keyword in C# which is also known immutable


values and are known at compile and run time and do not change their values at
run time like in any function for the life of application till the application is
running. You can assay their value by constructor when we call constructor with
“new” keyword.

9. What is Singleton Design Patterns and How to implement in C#?

Ensures a class has only one instance and provides a global point of access to it.

1. A singleton is a class that only allows a single instance of itself to be created,


and usually gives simple access to that instance.
2. Most commonly, singletons don't allow any parameters to be specified when
creating the instance, since a second request of an instance with a different
parameter could be problematic! (If the same instance should be accessed for all
requests with the same parameter then the factory pattern is more appropriate.)
3. There are various ways to implement the Singleton Pattern in C#. The following
are the common characteristics of a Singleton Pattern.

• A single constructor, that is private and parameterless.


• The class is sealed.
• A static variable that holds a reference to the single created instance, if any.
• A public static means of getting the reference to the single created instance,
creating one if necessary.

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.

12. Why to use access modifiers?

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.

In C# there are 5 different types of Access Modifiers.


ADO.Net
1. What is the differences Between DataReader and DataSet?

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?

Copy() Method the whole records with structure of DataSet.

private void btncopy_Click(object sender, EventArgs e)

DataSet daset = ds.Copy();

dataGridView2.DataSource = daset.Tables[0];

4. What does the parameter Initial Catalog define inside Connection String?

The database name to connect to mentioned in Initial Catalog.

5. Write sample code to open SQL connection

SqlConnection conn = new SqlConnection("Data Source=DatabaseServer;Initial


Catalog=Northwind;User ID=YourUserID;Password=YourPassword");

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.

// 1. Instantiate the connection

SqlConnection conn = new SqlConnection("Data Source=DatabaseServer;Initial


Catalog=Northwind;User ID=YourUserID;Password=YourPassword");

SqlDataReader rdr = null;

try
{
// 2. Open the connection
conn.Open();

// 3. Pass the connection to a command object


SqlCommand cmd = new SqlCommand("select * from Customers", conn);
//
// 4. Use the connection
//

// get query results


rdr = cmd.ExecuteReader();

// print the CustomerID of each record


while (rdr.Read())
{
Console.WriteLine(rdr[0]);
}
}

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.

2. How route table is created in ASP.NET MVC?


Ans. When an MVC application first starts, the Application_Start() method in global.asax
is called. This method calls the RegisterRoutes() method. The RegisterRoutes() method
creates the route table for MVC application

3. What is Test Driven Development (TDD)?


Ans:
TDD is a methodology which says, write your tests first before you write your code. In
TDD, tests drive your application design and development cycles. You do not do the
check-in of your code into source control until all of your unit tests pass.

4. What are different types of Filters in ASP.NET MVC?


Ans. The ASP.NET MVC framework provides five types of filters.
Authentication Filters - This filter is introduced with ASP.NET MVC5. The
IAuthenticationFilter interface is used to create CustomAuthentication filter. The
definition of this interface is given below-

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

5. Difference between partial view and render partial view.?

6. What are HTML Helpers in ASP.NET MVC?


Ans.
In HTML Helper is just a method that returns a HTML string. The string can represent any
type of content that you want. For example, you can use HTML Helpers to render
standard HTML tags like HTML <input>, <button> and <img> tags etc.
You can also create your own HTML Helpers to render more complex content such as a
menu strip or an HTML table for displaying database data

7. What is State Management techniques ?


Ans.
a)ViewData: instead creating dynamic properties we use properties of Model to
transport the Model data in View
b)ViewBag: we can create dynamic properties without using Model data.
c)Temp Data: in Single request we pass data from one controller to another controller.

8. How to enable and disable optimizations in ASP.NET MVC?

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;
}

9. What is unobtrusive AJAX?


Ans. ASP.NET MVC supports unobtrusive Ajax which is based on jQuery. The unobtrusive
Ajax means that you use helper methods to define your Ajax features, rather than adding
blocks of code throughout your views.
1st Way
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

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.

Class HomeController : Controller

[OutputCache(Duration = 20, VaryByParam = "none")]

public ActionResult Index()

ViewBag.Message = DateTime.Now.ToString();
return View();

12. What is advantages of Dependency Injection?

Ans. There are following advantages of DI:


 Reduces class coupling
 Increases code reusing
 Improves code maintainability
 Improves application testing

DI is a software design pattern that allow us to develop loosely coupled code. DI is a


great way to reduce tight coupling between software components. DI also enables us to
better manage future changes and other complexity in our software. The purpose of DI is
to make code maintainable.

=========================================================
===============

Entity Framework
1. What is Entity Framework?

Microsoft Entity Framework (EF) is an Object Relational Mapping framework that


provides an abstraction layer (a kind of mapping) between two incompatible systems (i.e.
Object oriented programming languages with Relational databases). It enables us to
interact with relational data in an object oriented way, meaning we can retrieve
and manipulate data as strongly typed objects using LINQ queries.

2. What is Entity Data Model (EDM)?

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).

3. What is .edmx file and what it contains?

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.

4. What are CSDL, SSDL and MSL sections in an EDMX file?


CSDL, SSDL and MSL are actually XML files.
CSDL (Conceptual Schema Definition Language) -is the conceptual abstraction which is
exposed to the application.
SSDL (Storage Schema Definition Language) –defines the mapping with our RDBMS data
structure.
MSL (Mapping Schema Language) -connects the CSDL and SSDL.

5. How to load related Entities in EF

In Entity Framework we can load related data in three ways

 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.]

7. What is Eager Loading?

The opposite of Lazy Loading is eager loading. Eager loading is the process of loading
related entities/ objects.

8. What is Explicit Loading?

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.

9. What are the types of development approaches in EF?

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

10. What are T4 templates?

Text Template Transformation Toolkit or T4 is a template based code generation engine.


We can go and write C# code in T4 templates (.tt is the extension) files and those C#
codes execute to generate the file as per the written C# logic.
T4 C# code:
<#@ template language=”“C#”” #>
Hello <# Write (”Mr.!”) #>
C# output:
Hello
Mr. !

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.

2. What are the types of LINQ?

LINQ to Objects
LINQ to XML
LINQ to Dataset
LINQ to SQL
LINQ to Entities

3. Define what is Where clause and Let clause?

Where clause: It allows adding some conditional filters to the query.


Let clause: It allows defining a variable and assigning it a value calculated from the data
values.

4. Explain what is lambda expressions in LINQ?


Lambda expression is referred as a unique function use to form delegates or expression
tree types, where right side is the output and left side is the input to the method. For
writing LINQ queries particularly, Lambda expression is used. Lambda expression used
=> operator.

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

6. Give example of get data from a table in LINQ to SQL.

supposed we have EmployeeDataContenxt() which contains all exmployee data.(emp


name,emp city)retrieve all emp who stays in Mumbai city and print in Console.

// EmployeeDataContenxt inherits from System.Data.Linq.DataContext.


EmployeeDataContenxt db = new EmployeeDataContenxt();

var EmployeeNames = from emp in db.Employee


where emp.City == "Mumbai"
select emp.EmpName;

foreach (var employee in EmployeeNames)


{
Console.WriteLine(employee);
=========================================================
====================

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

1. Which is the starting point of code execution in jQuery?

Ans: The starting point of jQuery code execution is $(document).ready() function which is
executed when DOM is loaded.

2. What does dollar sign ($) means in jQuery?

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(){
});

3. Can we have multiple document.ready() function on the same page?

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();
});

5. What is the difference between .js and .min.js?

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.

6. Why there are two different version of jQuery library?

Ans: jQuery library comes in 2 different versions.


1. Development 
2. Production/Deployment
The development version is quite useful at development time as jQuery is open source and if
you want to change something then you can make those changes in development version. But
the deployment version is minified version or compressed version so it is impossible to make
changes in it. Because it is compressed, so its size is very less than the production version which
affects the page load time.

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); 

Show table data


SELECT *FROM tbEmployee

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.

2. How to use Transaction in database? Explain structure of db Procedure

BEGIN TRANSACTION;
DELETE FROM HumanResources.JobCandidate
WHERE JobCandidateID = 13;
COMMIT;

3. Different types of UDF?


Scalar & Table Valued function

4. How to execute Table Valued function?

Ans: Select * from dbo.Function-Name(parameters)

5. What is Primary Key, Composite Key, Unique Key?

6. What is Database Cursor?

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

Table A has 4 records and Table B has 10 records.


Table A and Table B has 2 records common.
Now how many rows will return if we write :-
Left join query (Ans. 4)
Right Join (Ans. 10)
Union (Ans. 12)
Union ALL (Ans. 14)

7. Different Types of Temporary Tables in SQL? Explain


Ans: #Table & ## Table)

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).

10. Difference between varchar and Nvarchar


Ans:- Nvarchar stores UNICODE data.
Nvarchar uses 2 bytes per character whereas varchar uses 1 byte.
=========================================================
==================

Documentation :
1. What type of documentation you have created ?
1)DDD
2)FSD
3)TSD
4)Test Cases
5)Code Review Document

You might also like