Important Topics
Important Topics
delete from EmpDup where EmpID in(select EmpID from EmpDup group by EmpId having
count(*) >1)
• With CTE
With CTE_Duplicates as
from EmpDup )
Synchronous (Classic Web-Application Model) : A synchronous request blocks the client until
operation completes i.e. browser is unresponsive. In such case, javascript engine of the browser
is blocked.
ASP.Net MVC
Multiple view support - Due to the separation of the model from the view, the user interface
can display multiple views of the same data at the same time.
Change Accommodation - User interfaces tend to change more frequently than business rules
(different colors, fonts, screen layouts, and levels of support for new devices such as cell
phones or PDAs) because the model does not depend on the views, adding new types of views
to the system generally does not affect the model. As a result, the scope of change is confined
to the view.
More Control - The ASP.NET MVC framework provides more control over HTML, JavaScript
and CSS than the traditional Web Forms.
Testability - ASP.NET MVC framework provides better testability of the Web Application and
good support for the test driven development too.
Lightweight - ASP.NET MVC framework doesn’t use View State and thus reduces the
bandwidth of the requests to an extent.
In MVC, controllers define action methods and these action methods generally have a one-to-
one relationship with UI controls such as clicking a button or a link, etc.
But many times we would like to perform some action before or after a particular operation. For
achieving this functionality, ASP.NET MVC provides feature to add pre and post action
behaviors on controller's action methods.
Action Filters are additional attributes that can be applied to either a controller section or the
entire controller to modify the way in which action is executed. These attributes are special .NET
classes derived from System.Attribute which can be attached to classes, methods, properties
and fields.
ASP.NET MVC provides the following action filters:
Output Cache: This action filter caches the output of a controller action for a specified amount
of time.
Handle Error: This action filter handles errors raised when a controller action executes.
Authorize: This action filter enables you to restrict access to a particular user or role.
Output Cache
E.g.: Specifies the return value to be cached for 10 seconds.
publicclassActionFilterDemoController: Controller
{
[HttpGet]
OutputCache(Duration = 10)]
publicstringIndex()
{
returnDateTime.Now.ToString("T");
}
}
7. Explain what is routing in MVC? What are the three segments for routing important?
Routing is a mechanism which is used to handle the incoming requests coming from browsers
and it represent the particular action rather than any static or physical files. In ASP.NET, the Url
hits any resources or files which physically exists but ASP.NET MVC Routing represents action.
It is an approach to perform some action based on their definition defined in RouteConfig.cs
• Convention Routing
• Attribute Routing
Convention Routing :
Convention Routing approaches the routing problem general-case-first; by default, you are
given a route that will probably match most if not all of your routes, and are asked to define if
there are any more specific routes you would also like to handle.
• routes is the Route Table of type RouteCollection, and stores all of the possible routes
we can match for a given URL.
• A call to IgnoreRoute allows us to tell ASP.NET to ignore any URL that matches that
tokenized structure and process it normally.
Attribute Routing :
Attribute Routing (introduced in MVC 5) is the ability to add routes to the Route Table via
attributes so that the route definitions are in close proximity to their corresponding actions. We
will still populate the Route Table, but we will do it in a different manner.
If you want to use Attribute Routing, you have to enable it by calling MapMvcAttributeRoutes
on the RouteCollection for your app (usually this is done in RouteConfig):
Simple Example
A simple example of Attribute Routing might look like this
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such
as a .aspx file in a Web Forms application. A handler can also be a class that processes the
request, such as a controller in an MVC application.
Default Route:
The default ASP.NET MVC project templates add a generic route that uses the following URL
convention to break the URL for a given request into three named segments.
URL: "{controller}/{action}/{id}"
9. Mention what is the difference between Temp data, View, and View Bag?
In ASP.NET MVC there are three ways to pass/store data between the controllers and views.
ViewData
• ViewData is used to pass data from controller to view.
• It is derived from ViewDataDictionary class.
• It is available for the current request only.
• Requires typecasting for complex data type and checks for null values to avoid error.
• If redirection occurs, then its value becomes null.
ViewBag
• ViewBag is also used to pass data from the controller to the respective view.
• ViewBag is a dynamic property that takes advantage of the new dynamic features in C#
4.0
• It is also available for the current request only.
• If redirection occurs, then its value becomes null.
• Doesn’t require typecasting for complex data type.
TempData
• TempData is derived from TempDataDictionary class
• TempData is used to pass data from the current request to the next request
• It keeps the information for the time of an HTTP Request. This means only from one
page to another. It helps to maintain the data when we move from one controller to
another controller or from one action to another action
• It requires typecasting for complex data type and checks for null values to avoid error.
Generally, it is used to store only one time messages like the error messages and
validation messages
A partial view is a chunk of HTML that can be safely inserted into an existing DOM.
Partial view is a reusable view (like a user control) which can be embedded inside other view.
11. Explain what is the difference between View and Partial View?
View:
• It contains the layout page.
• Before any view is rendered, viewstart page is rendered.
• View might have markup tags like body, html, head, title, meta etc.
• View is not lightweight as compare to Partial View.
Partial View:
• It does not contain the layout page.
• Partial view does not verify for a viewstart.cshtml.We cannot put common code for a
partial view within the viewStart.cshtml.page.
• Partial view is designed specially to render within the view and just because of that it
does not consist any mark up.
• We can pass a regular view to the RenderPartial method.
In ASP.NET MVC 5.0 we have a new attribute route,cBy using the "Route" attribute we can
define the URL structure. For example in the below code we have decorated the "GotoAbout"
action with the route attribute. The route attribute says that the "GotoAbout" can be invoked
using the URL structure "Users/about".
With MVC, HTML helpers are much like traditional ASP.NET Web Form controls.
Just like web form controls in ASP.NET, HTML helpers are used to modify HTML. But HTML
helpers are more lightweight. Unlike Web Form controls, an HTML helper does not have an
event model and a view state.
In most cases, an HTML helper is just a method that returns a string.
With MVC, you can create your own helpers, or use the built in HTML helpers.
ASP.NET MVC has always supported the concept of "view engines" - which are the pluggable
modules that implement different template syntax options. The "default" view engine for
ASP.NET MVC uses the same .aspx/.ascx/. master file templates as ASP.NET Web Forms.
Other popular ASP.NET MVC view engines are Spart&Nhaml.
MVC 3 has introduced a new view engine called Razor.
Why is Razor?
Authentication is giving access to the user for a specific service by verifying his/her identity
using his/her credentials like username and password or email and password. It assures that
the correct user is authenticated or logged in for a specific service and the right service has
been provided to the specific user based on their role that is nothing but authorization.
ASP.NET forms authentication occurs after IIS authentication is completed. You can configure
forms authentication by using forms element with in web.config file of your application. The
default attribute values for forms authentication are shown below:
<system.web>
<authenticationmode="Forms">
<formsloginUrl="Login.aspx" protection="All" timeout="30" name=".ASPXAUTH" path="/"
requireSSL="false" slidingExpiration="true" defaultUrl="default.aspx"
cookieless="UseDeviceProfile" enableCrossAppRedirects="false" />
</authentication>
</system.web>
From ASP.Net MVC 2.0 Microsoft provided a new feature in MVC applications, Areas. Areas
are just a way to divide or “isolate” the modules of large applications in multiple or separated
MVC.
When you add an area to a project, a route for the area is defined in an AreaRegistration file.
The route sends requests to the area based on the request URL. To register routes for areas,
you add code to theGlobal.asax file that can automatically find the area routes in the
AreaRegistration file.
AreaRegistration.RegisterAllAreas();
A display mode is a powerful tool for all mobile-based apps development. However, it is not
limited to mobile web apps but it can also be used to display any alternative view, which is tied
to an existing controller. Display Modes practically give you another level of flexibility on top of
the default capabilities we saw in the last section. Display Modes can also be used along with
the previous feature so the users will simply build off of the site they just created. It simplifies the
ways to implement different versions of view for different devices.
18. Explain the concept of MVC Scaffolding?
ASP.NET Scaffolding is a code generation framework for ASP.NET Web applications. Using
scaffolding can reduce the amount of time to develop standard data operations in your project.
Scaffolding consists of page templates, entity page templates, field page templates, and filter
templates. These templates are called Scaffold templates and allow you to quickly build a
functional data-driven Website.
Scaffolding Templates:
Create: It creates a View that helps in creating a new record for the Model. It automatically
generates a label and input field for each property in the Model.
Delete: It creates a list of records from the model collection along with the delete link with delete
record.
Details: It generates a view that displays the label and an input field of the each property of the
Model in the MVC framework.
Edit: It creates a View with a form that helps in editing the current Model. It also generates a
form with label and field for each property of the model.
List: It generally creates a View with the help of a HTML table that lists the Models from the
Model Collection. It also generates a HTML table column for each property of the Model.
This is very necessary for when we want to add a specific constraint to our URL. Say, for
example we want to set some constraint string after our host name:
It's very simple to implement, just open the RouteConfig.cs file and you will find the routing
definition in that. And modify the routing entry as in the following. We will see that we have
added “abc” before.
Controller name, now when we browse we need to specify the string in the URL, as in the
following:
The main purpose of using Output Caching is to dramatically improve the performance of an
ASP.NET MVC Application. It enables us to cache the content returned by any controller
method so that the same content does not need to be generated each time the same controller
method is invoked. Output Caching has huge advantages, such as it reduces server round trips,
reduces database server round trips, reduces network traffic etc.
Bundling and minification are two new techniques introduced to improve request load time. It
improves load time by reducing the number of requests to the server and reducing the size of
requested assets (such as CSS and JavaScript).
Bundling: It lets us combine multiple JavaScript (.js) files or multiple cascading style sheet (.css)
files so that they can be downloaded as a unit, rather than making individual HTTP requests.
Minification: It squeezes out whitespace and performs other types of compression to make the
downloaded files as small as possible. At runtime, the process identifies the user agent, for
example IE, Mozilla, etc. and then removes whatever is specific to Mozilla when the request
comes from IE.
The ValidationSummary helper method generates an unordered list (ul element) of validation
messages that are in the ModelStateDictionary object.
The ValidationSummary can be used to display all the error messages for all the fields. It can
also be used to display custom error messages.
DataAnnotations
1) ASP.NET MVC uses DataAnnotations attributes for validation.
2) DataAnnotations attributes can be applied to the properties of the model class to indicate the
kind of value the property will hold.
3) The following validation attributes available by default
• Required
• StringLength
• Range
• RegularExpression
• CreditCard
• CustomValidation
• EmailAddress
• FileExtension
• MaxLength
• MinLength
• Phone
4) Use ValidationSummary to display all the error messages in the view.
5) Use ValidationMessageFor or ValidationMessage helper method to display field level error
messages in the view.
6) Check whether the model is valid before updating in the action method using
ModelState.IsValid.
7) Enable client side validation to display error messages without postback effect in the browser.
ASP.Net MVC has an attribute called "HandleError" that provides built-in exception filters. The
HandleError attribute in ASP.NET MVC can be applied over the action method as well as
Controller or at the global level. The HandleError attribute is the default implementation of
IExceptionFilter. When we create a MVC application, the HandleError attribute is added within
the Global.asax.cs file and registered in the Application_Start event.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
}
Razor View Engine introduced a new layout named _ViewStart which is applied on all view
automatically. Razor View Engine firstly executes the _ViewStart and then start rendering the
other view and merges them.
DataAnnotation plays a vital role in added validation to properties while designing the model
itself. This validation can be added for both the client side and the server side.
Some of the DataAnnotation used for validation are given below:
Required
RegularExpression
Range
StringLength
MaxLength
The HandleErrorAttribute allows you to use a custom page for this error. First you need to
update your web.config file to allow your application to handle custom errors.
<system.web>
<customErrors mode="On">
</system.web>
[HandleError]
public class HomeController: Controller
{
[HandleError(View = "CustomErrorView")]
publicActionResultThrowException()
{
throw new ApplicationException();
}
}
28. What is the use of remote validation in MVC?
Remote validation is the process where we validate specific data posting data to a server
without posting the entire form data to the server. Let's see an actual scenario, we have a
requirement to validate an email address, whether it already exists in the database. Remote
validation is useful for that; without posting all the data we can validate only the email address
supplied by the user.
UserModel:
public class UserModel
{
[Required]
public string UserName
{
get;
set;
}
[Remote("CheckExistingEmail", "Home", ErrorMessage = "Email already exists!")]
public string UserEmailAddress
{
get;
set;
}
}
Controller:
public ActionResult CheckExistingEmail(string UserEmailAddress)
{
bool ifEmailExist = false;
try
{
ifEmailExist = UserEmailAddress.Equals("[email protected]") ? true : false;
return Json(!ifEmailExist, JsonRequestBehavior.AllowGet);
} catch (Exception ex)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
}
@RenderSection(“TestSection”)
@section TestSection{
<h1>Test Content</h1>
If any child page does not have this section defined then error will be thrown so to avoid that we
can render the HTML like this –
@RenderSection(“TestSection”, required: false)
In MVC all public methods have been treated as Actions. So if you are creating a method and if
you do not want to use it as an action method then the method has to be decorated with
“NonAction” attribute as shown below –
[NonAction]
public void TestMethod()
{
// Method logic
}
RenderBody is like ContentPlaceHolder in web forms. This will exist in layout page and it will
render the child pages/views. Layout page will have only one RenderBody() method.
RenderPage also exists in Layout page and multiple RenderPage() can be there in Layout
page.
Result of the method — “RenderPartial” is directly written to the HTML response. This method
does not return anything (void). This method also does not depend on action methods.
RenderPartial() method calls “Write()” internally and we have to make sure that “RenderPartial”
method is enclosed in the bracket. Below is the sample code snippet –
@{Html.RenderPartial(“TestPartialView”); }
With model binding, MVC framework converts the http request values (from query string or form
collection) to action method parameters. These parameters can be of primitive type or complex
type.
Binding to Primitive type
HttpGET request embeds data into a query string.
This method is used to render the specified partial view as an HTML string. This method does
not depend on any action methods. We can use this like below –
@Html.Partial(“TestPartialView”)
1. What is JQuery
JQuery is a cross-browser lightweight JavaScript library. In simple words jQuery has been
designed to make navigation to any element easier, or adding/invoking event handlers on your
HTML page and also simplify the way you access the elements in your web pages, provide help
in working with client-side events, enable visual effects like animation, and make it easier to use
Ajax in your applications.
2. What is JQuery.noConflict?
jQuery no-conflict is an option given by jQuery to overcome the conflicts between the different
js frameworks or libraries. When we use jQuery no-conflict mode, we are replacing the $ to a
new variable and assigning to jQuery some other JavaScript libraries. Also use the $ (Which is
the default reference of jQuery) as a function or variable name what jQuery has. And in our
development life, we are not at all strict to only jQuery.
3. What is a CDN?
Content Delivery Network (CDN) in simple terms is a collection of servers spread across the
globe. In other words, a CDN is a network of servers in which each request will go to the closest
server.
For any web application, data can be categorized into either static or dynamic content. Dynamic
content is the one that generally comes from a database. Static content is like CSS, images,
JavaScript, flash files, video files and so on.
4. What are selectors in jQuery and how many types of selectors are there?
The basic operation in jQuery is selecting an element in DOM. This is done with the help of
$() construct with a string parameter containing any CSS selector expression. $() will return zero
or more DOM elements on which we can apply an effect or style.
$(document).ready() indicates that code in it needs to be executed once the DOM got loaded. It
won't wait for the images to load for executing the jQuery script. We created an anonymous
function inside ready() function to hide div1.
As we discussed earlier, $() accepts a string parameter having tag name [like div, p] or Element
Id or class name as shown in the following table.
The "jQuery.each()" function is a general function that will loop through a collection (object
type or array type)
In the "jQuery.each()" method we're able to pass in an arbitrary array or object in which for
each item will have the callback function executed .
Example :
<script type="text/javascript">
$(document).ready(function () {
});
});
</script>
Output :
Position is : 1 And Value is : Goergie
jQuery.attr()
Gets the value of an attribute for the first element in the set of matched elements.
Whereas:
jQuery. prop ()
Gets the value of a property for the first element in the set of matched elements.
For example
As shown above, “id”, "type” and “value" are attributes of the input elements.
jQuery UI enable our applications to have a cool user interface and animation in a faster way. It
is the set of plug-ins that include interface interactions, effects, animations, widgets and themes
built on the JavaScript Library.
Interactions
We can use interactions for basic mouse-based behaviours to any element. Examples of
Interactions are the following:
Draggable
Droppable
Resizable
Selectable
Sortable
$(window).load is an event that fires when the DOM and all the content (everything) on the page
is fully loaded. This event is fired after the ready event.
$(window).load(function() {
alert("Window load event fired");
});
$(document).ready(function() {
alert("document ready event fired");
});
</script>
In the preceding JavaScript, we created an anonymous function that contains an alert message.
So, when the preceding two events are fired an alert window will pop-up.
In most cases, the script can be executed as soon as the DOM is fully loaded, so ready() is
usually the best place to write your JavaScript code. But there could be some scenario where you
might need to write scripts in the load() function. For example, to get the actual width and height
of an image.
As we know the $(window).load event is fired once the DOM and all the CSS, images and
frames are fully loaded. So, it is the best place to write the jQuery code to get the actual image
size or to get the details of anything that is loaded just before the load event is raised.
9. How to handle Controls attribute Using jQuery?
For handle Controls attribute using jQuery we used .addClass(), .removeClass(), .css(),
.toggleClass(), etc to manage all css and html attributes of any html control.
Chaining is a powerful feature of jQuery. Chaining means specifying multiple functions and/or
selectors to an element.
Chaining reduces the code segment and keeps it very clean and easy to understand. Generally
chaining uses the jQuery built in functions that makes compilation a bit faster.
$("#div2").html($("#txtBox").prop("readonly")) + '</br>';
$("#div3").html($("#txtBox").attr("readonly"));
});
The code segment above is described by the following image:
$.ajax () Method
JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:
async
type
url
data
datatype
success
error
Let’s have a detailed overview:
async
The ajax() method is used to do an AJAX (asynchronous HTTP) request. It provides more
control of the data sending and on response data. It allows the handling of errors that occur
during a call and the data if the call to the ajax page is successful.
Here is the list of some basic parameters required for jQuery.ajax Method:
• type: Specifies the type of request (GET or POST).
• url: Specifies the URL to send the request to. The default is the current page.
• contentType: The content type used when sending data to the server. The default is
"application/x-www-form-urlencoded".
• dataType: The data type expected of the server response.
• data: Specifies data to be sent to the server.
• success(result,status,xhr): A function to run when the request succeeds.
• error(xhr,status,error): A function to run if the request fails.
It is a framework which helps us to build/develop HTTP services. So there will a client server
communication using HTTP protocol.
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.
Routing is the mechanism of pattern matching as we have in MVC. These routes will get
registered in Route Tables. Below is the sample route in Web API –
Routes.MapHttpRoute(
Name: “MyFirstWebAPIRoute”,
routeTemplate: “api/{controller}/{id}
WCF
• It is framework build for building or developing service oriented applications.
• WCF can be consumed by clients which can understand XML.
• WCF supports protocols like – HTTP, TCP, Named Pipes etc.
Web API
• It is a framework which helps us to build/develop HTTP services
• Web API is an open source platform.
• It supports most of the MVC features which keep Web API over WCF.
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.
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.
Below are some of the differences between MVC and Web API
MVC
• MVCis used to create a web app, in which we can build web pages.
• For JSONit 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.
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
11) How we can restrict access to methods with specific HTTP verbs in Web API?
Attribute programming is used for this functionality. Web API will support to restrict access of
calling methods with specific HTTP verbs. We can define HTTP verbs as attribute over method
as shown below.
[HttpPost]
public void UpdateTestCustomer(Customer c)
{
TestCustomerRepository.AddCustomer(c);
}
13) List out the steps to be made for Web API to work in Web Forms?
14) Explain how to give alias name for action methods in Web API?
Using attribute “ActionName” we can give alias name for Web API actions. Eg:
[HttpPost]
[ActionName(“AliasTestAction”)]
public void UpdateTestCustomer(Customer c)
{
TestCustomerRepository.AddCustomer(c);
}
15) What is the difference between MVC Routing and Web API Routing?
There should be atleast one route defined for MVC and Web API to run MVC and Web API
application respectively. In Web API pattern we can find “api/” at the beginning which makes
it distinct from MVC routing. In Web API routing “action” parameter is not mandatory but it can
be a part of routing.
Exception filters will be executed whenever controller methods (actions) throws an exception
which is unhandled. Exception filters will implement “IExceptionFilter” interface.
Below are the methods to pass the complex types in Web API –
• Using ArrayList
• Newtonsoft JArray
paramList.Add(c);
paramList.Add(p);
config.Routes.MapHttpRoute(
name: “MyRoute”,//route name
routeTemplate: “api/{controller}/{action}/{id}”,//as you can see “api” is at the beginning.
defaults: new { id = RouteParameter.Optional }
);
Below are the list of classes which can be used for error handling –
• HttpResponseException
• Exception Filters
• Registering Exception Filters
• HttpError
This returns the HTTP status code what you specify in the constructor. Eg :
• From Action
• From Controller
• Global registration
23) Write a code snippet to register exception filters from action?
Below is the code snippet for registering exception filters from action –
[NotImplExceptionFilter]
public TestCustomer GetMyTestCustomer(int custid)
{
//Your code goes here
}
Below is the code snippet for registering exception filters from controller –
[NotImplExceptionFilter]
public class TestCustomerController : Controller
{
//Your code goes here
}
HttpError will be used to throw the error info in response body. “CreateErrorResponse” method
is used along with this, which is an extension method defined in
“HttpRequestMessageExtensions”.
26) Write a code snippet to show how we can return 404 error from HttpError?
Below is the code snippet for returning 404 error from HttpError –
config.EnableSystemDiagnosticsTracing();
It is also called MIME, which is used to identify the data . In Html, media types is used to
describe message format in the body.
• Image/Png
• Text/HTML
• Application/Json
Media Formatters in Web API can be used to read the CLR object from our HTTP body and
Media formatters are also used for writing CLR objects of message body of HTTP.
“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.
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.
In case validation fails here it returns HTTP response which contains validation errors.
• FROM clause
• WHERE clause
• GROUP BY clause
• HAVING clause
• SELECT clause
• ORDER BY clause
• TOP clause
• DML (Data Manipulation Language): These statements are used to manipulate the data
in records. Commonly used DML statements are Insert, Update, and Delete.
The Select statement is used as partial DML statement that is used to select all or
relevant records in the table.
• DCL (Data Control Language): These statements are used to set privileges such as
Grant and Revoke database access permission to the specific user.
Why do we use SQL constraints? Which constraints we can use while creating
database in SQL?
Constraints are used to set the rules for all records in the table. If any constraints get violated
then it can abort the action that caused it.
Constraints are defined while creating the database itself with CREATE TABLE statement or
even after the table is created once with ALTER TABLE statement.
NOT NULL: That indicates that the column must have some value and cannot be left null
UNIQUE: This constraint is used to ensure that each row and column has unique value and no
value is being repeated in any other row or column
PRIMARY KEY: This constraint is used in association with NOT NULL and UNIQUE
constraints such as on one or the combination of more than one columns to identify the particular
record with a unique identity.
FOREIGN KEY: It is used to ensure the referential integrity of data in the table and also
matches the value in one table with another using Primary Key
CHECK: It is used to ensure whether the value in columns fulfills the specified condition
In simple word, we can say that a transaction means a group of SQL queries executed on
database records.
Atomicity: Ensures the completeness of all transactions performed. Checks whether every
transaction is completed successfully if not then transaction is aborted at the failure point and the
previous transaction is rolled back to its initial state as changes undone
Consistency: Ensures that all changes made through successful transaction are reflected properly
on database
Isolation: Ensures that all transactions are performed independently and changes made by one
transaction are not reflected on other
Durability: Ensures that the changes made in database with committed transactions persist as it
is even after system failure.
SQL Aggregate Functions calculates values from multiple columns in a table and returns a single
value.
Scalar Functions are used to return a single value based on the input values. Scalar Functions are
as follows
Triggers in SQL is kind of stored procedures used to create a response to a specific action
performed on the table such as Insert, Update or Delete. You can invoke triggers explicitly on the
table in the database.
Action and Event are two main components of SQL triggers when certain actions are performed
the event occurs in response to that action.
A View can be defined as a virtual table that contains rows and columns with fields from one or
more table.
SQL CREATE and REPLACE can be used for updating the view.
SQL GRANT and REVOKE commands are used to implement privileges in SQL multiple user
environments. The administrator of the database can grant or revoke privileges to or from users
of database object like SELECT, INSERT, UPDATE, DELETE, ALL etc.
GRANT Command: This command is used provide database access to user apart from an
administrator.
In above syntax WITH GRANT OPTIONS indicates that the user can grant the access to another
user too.
REVOKE Command: This command is used provide database deny or remove access to
database objects.
SQL Injection is a type of database attack technique where malicious SQL statements are
inserted into an entry field of database such that once it is executed the database is opened for an
attacker. This technique is usually used for attacking Data-Driven Applications to have an access
to sensitive data and perform administrative tasks on databases.
NVL function is used to convert the null value to its actual value.
Correlated subquery: These are queries which select the data from a table referenced in the outer
query. It is not considered as an independent query as it refers to another table and refers the
column in a table.
Non-Correlated subquery: This query is an independent query where the output of subquery is
substituted in the main query.
• One table can have only one clustered index but multiple nonclustered indexes.
• Clustered indexes can be read rapidly rather than non-clustered indexes.
• Clustered indexes store data physically in the table or view and non-clustered indexes do
not store data in table as it has separate structure from data row
• The basic difference in both is DELETE is DML command and TRUNCATE is DDL
• DELETE is used to delete a specific row from the table whereas TRUNCATE is used to
remove all rows from the table
• We can use DELETE with WHERE clause but cannot use TRUNCATE with it.
TRUNCATE removes all rows from the table which cannot be retrieved back, DROP removes
the entire table from the database and it cannot be retrieved back.
Normalization is used to organize the data in such manner that data redundancy will never occur
in the database and avoid insert, update and delete anomalies.
Denormalization refers to a technique which is used to access data from higher to lower forms of
a database. It helps the database managers to increase the performance of the entire infrastructure
as it introduces redundancy into a table. It adds the redundant data into a table by incorporating
database queries that combine data from various tables into a single table.
The relationship can be defined as the connection between more than one tables in the database.
A stored procedure is a collection of SQL statements which can be used as a function to access
the database. We can create these stored procedures previously before using it and can execute
these them wherever we require and also apply some conditional logic to it. Stored procedures
are also used to reduce network traffic and improve performance.
What is a Cursor?
A cursor is a database object which is used to manipulate data in a row-to-row manner.
• Declare Cursor
• Open Cursor
• Retrieve row from the Cursor
• Process the row
• Close Cursor
• Deallocate Cursor
The index can be defined as the way to retrieve the data more quickly. We can define indexes
using CREATE statements.
Both Char and Varchar2 are used for characters datatype but varchar2 is used for character
strings of variable length whereas Char is used for strings of fixed length. For example, char(10)
can only store 10 characters and will not be able to store a string of any other length whereas
varchar2(10) can store any length i.e 6,8,2 in this variable.
Write a SQL query to get the third highest salary of an employee from employee_table?
SELECT TOP 1 salary
FROM (
SELECT TOP 3 salary
FROM employee_table
ORDER BY salary DESC) AS emp
ORDER BY salary ASC;
This statement allows conditional update or insertion of data into a table. It performs an
UPDATE if a row exists, or an INSERT if the row does not exist.
HAVING clause can be used only with SELECT statement. It is usually used in a GROUP BY
clause and whenever GROUP BY is not used, HAVING behaves like a WHERE clause.
Having Clause is only used with the GROUP BY function in a query whereas WHERE Clause is
applied to each row before they are a part of the GROUP BY function in a query.
Aggregate functions are used to evaluate mathematical calculation and returns a single value.
These calculations are done from the columns in a table. For example- max(),count() are
calculated with respect to numeric.
Scalar functions return a single value based on the input value. For example – UCASE(),
NOW() are calculated with respect to string.
There are a lot of ways to fetch characters from a string. For example:
Local variables:
These variables can be used or exist only inside the function. These variables are not used or
referred by any other function.
Global variables:
These variables are the variables which can be accessed throughout the program. Global
variables cannot be created whenever that function is called.
STUFF Function: This function is used to overwrite existing character or inserts a string into
another string. Syntax:
STUFF(string_expression,start, length, replacement_characters)
where,
string_expression: it is the string that will have characters substituted
start: This refers to the starting position
length: It refers to the number of characters in the string which are substituted.
replacement_string: They are the new characters which are injected in the string.
REPLACE function: This function is used to replace the existing characters of all the
occurrences. Syntax:
REPLACE (string_expression, search_string, replacement_string)
Here every search_string in the string_expression will be replaced with the replacement_string.
--------------------- Sql Server End---
• Scope
• Controller
• Model
• View
• Services
• Data Binding
• Directives
• Filters
• Testable
A core feature of AngularJS, directives are attributes that allow you to invent new HTML syntax,
specific to your application. They are essentially functions that execute when the Angular
compiler finds them in the DOM. Some of the most commonly used directives are ng-app,ng-
controller and ng-repeat.
• Element directives
• Attribute directives
• CSS class directives
• Comment directives
Controllers are Javascript functions which provide data and logic to HTML UI. As the name
suggests, they control how data flows from the server to HTML UI.
What is Angular Expression? How do you differentiate between Angular expressions and
JavaScript expressions?
Angular expressions are code snippets that are usually placed in binding such as {{ expression }}
similar to JavaScript.
The main differences between Angular expressions and JavaScript expressions are:
Context: The expressions are evaluated against a scope object in Angular, while Javascript
expressions are evaluated against the global window
Forgiving: In Angular expression, the evaluation is forgiving to null and undefined whereas in
JavaScript undefined properties generate TypeError or ReferenceError
No Control Flow Statements: We cannot use loops, conditionals or exceptions in an Angular
expression
Filters: In Angular, unlike JavaScript, we can use filters to format data before displaying it
Compile function is used for template DOM Manipulation and to collect all the directives.
Link function is used for registering DOM listeners as well as instance DOM manipulation and is
executed once the template has been cloned.
Scope is an object that refers to the application model. It is an execution context for expressions.
Scopes are arranged in hierarchical structure which mimic the DOM structure of the application.
Scopes can watch expressions and propagate events. The characteristics of Scope are:
• Scopes provide APIs ($apply) to propagate any model changes through the system into
the view from outside of the “Angular realm” (controllers, services, Angular event
handlers).
• Scopes can be nested to limit access to the properties of application components while
providing access to shared model properties. Nested scopes are either “child scopes” or
“isolate scopes”. A “child scope” (prototypically) inherits properties from its parent
scope. An “isolate scope” does not. See isolated scopes for more information.
• Scopes provide context against which expressions are evaluated. For example
{{username}} expression is meaningless, unless it is evaluated against a specific scope
which defines the username property.
AngularJS combines the functionalities of most third party libraries and supports individual
functionalities required to develop HTML5 Apps. While Backbone.js does these jobs
individually.
An injector is a service locator, used to retrieve object instance as defined by provider, instantiate
types, invoke methods, and load modules.
Factory method is used for creating a directive. It is invoked when the compiler matches the
directive for the first time. We can invoke the factory method using $injector.invoke.
Result: When declaring factoryName as an injectable argument you will be provided with the
value that is returned by invoking the function reference passed to module.factory.
No. Only one AngularJS application can be auto-bootstrapped per HTML document. The first
ngApp found in the document will be used to define the root element to auto-bootstrap as an
application. If another ng-app directive has been placed then it will not be processed by
AngularJS and we will need to manually bootstrap the second app, instead of using second ng-
app directive.
Internationalization is a way in which you can show locale specific information on a website.
AngularJS supports inbuilt internationalization for three types of filters: currency, date and
numbers. To implement internalization, we only need to incorporate corresponding js according
to locale of the country. By default it handles the locale of the browser.
Every application has a single root scope. All other scopes are descendant scopes of the root
scope. Scopes provide separation between the model and the view, via a mechanism for watching
the model for changes. They also provide event emission/broadcast and subscription facility.
Yes, we can create nested controllers in AngularJS. Nested controllers are defined in hierarchical
manner while using in View.
Bootstrapping in AngularJS is nothing but initializing, or starting the Angular app. AngularJS
supports automatic and manual bootstrapping.
• Automatic Bootstrapping: this is done by adding ng-app directive to the root of the
application, typically on the tag or tag if you want angular to bootstrap your application
automatically. When angularJS finds ng-app directive, it loads the module associated
with it and then compiles the DOM.
• Manual Bootstrapping: Manual bootstrapping provides you more control on how and
when to initialize your angular App. It is useful where you want to perform any other
operation before Angular wakes up and compile the page.
What does SPA (Single Page Application) mean? How can we implement SPA with
Angular?
Single Page Applications (SPAs) are web apps that load a single HTML page and dynamically
update that page as the user interacts with the app. In an SPA the page never reloads, though
parts of the page may refresh. This reduces the round trips to the server to a minimum.
It’s a concept where we create a single shell page or master page and load the webpages inside
that master page instead of loading pages from the server by doing post backs. We can
implement SPA with Angular using Angular routes. You can read up about SPAs here.
Why AngularJS?
AngularJS lets us extend HTML vocabulary for our application resulting in an expressive,
readable, and quick to develop environment . Some of the advantages are:
Yes AngularJS is compatible with the following browsers: Safari, Chrome, Firefox, Opera 15,
IE9 and mobile browsers (Android, Chrome Mobile, iOS Safari).
It is a five-step process:
‘Promises’ are post processing logics which are executed after some operation/action is
completed whereas ‘deferred’ is used to control how and when those promise logics will execute.
We can think about promises as “WHAT” we want to fire after an operation is completed while
deferred controls “WHEN” and “HOW” those promises will execute.
“$q” is the angular service which provides promises and deferred functionality.
Object on Demand is also called Lazy loading pattern, Lazy loading delays the initialization of
object. This is a new feature of C# 4.0 and can be used when we are working with large objects
when it is not in use. This article will explain you about "Lazy" class.
Suppose we have Candidate class and EducationProfile class. One candidate can have more
than one EducationProfile (like: Bachelors (BBA), Master(MBA)). If you want to show the
EducationProfile with the respective Candidate, you need to load EducationProfiles associated
with that Candidate. If you are loading an Education Profile with the respective candidate you
need to initialize a Candidate object and that is supposed to be huge .
For avoiding the situation you can use the Lazy Loading Pattern. Loading of EdutioanProfile will
only happen when you will use EducationProfile list. And this will make sure fast action in
comparison to the normal one and performance will also increase.
Syntax :
Lazy<list<educationproile>> educationProileList;
2. WHERE
3. GROUP BY
4. HAVING
5. SELECT
6. DISTINCT
7. ORDER BY
8. LIMIT / OFFSET
Query to List all hierarchical parents and siblings and their childrens, but not list own
childrens
WITH CT AS
(
SELECT * FROM T WHERE AccountID=4
UNION ALL
SELECT T.* FROM T
JOIN CT ON T.ParentID = CT.AccountId
)
SELECT * FROM T WHERE AccountID
NOT IN (SELECT AccountID FROM CT)
OR
Why do we use SQL constraints? Which constraints we can use while creating database in
SQL?
Constraints are used to set the rules for all records in the table. If any constraints get violated
then it can abort the action that caused it.
Constraints are defined while creating the database itself with CREATE TABLE statement or
even after the table is created once with ALTER TABLE statement.
• NOT NULL: That indicates that the column must have some value and cannot be left
null
• UNIQUE: This constraint is used to ensure that each row and column has unique value
and no value is being repeated in any other row or column
• PRIMARY KEY: This constraint is used in association with NOT NULL and UNIQUE
constraints such as on one or the combination of more than one columns to identify the
particular record with a unique identity.
• FOREIGN KEY: It is used to ensure the referential integrity of data in the table and also
matches the value in one table with another using Primary Key
• CHECK: It is used to ensure whether the value in columns fulfills the specified
condition.
Both Char and Varchar2 are used for characters datatype but varchar2 is used for character
strings of variable length whereas Char is used for strings of fixed length. For example, char(10)
can only store 10 characters and will not be able to store a string of any other length whereas
varchar2(10) can store any length i.e 6,8,2 in this variable.
What is the difference between clustered and non clustered index in SQL?
The differences between the clustered and non clustered index in SQL are :
Clustered index is used for easy retrieval of data from the database and its faster whereas reading
from non clustered index is relatively slower.
Clustered index alters the way records are stored in a database as it sorts out rows by the column
which is set to be clustered index whereas in a non clustered index, it does not alter the way it
was stored but it creates a separate object within a table which points back to the original table
rows after searching.
One table can only have one clustered index whereas it can have many non clustered index.
What is an Index?
An index refers to a performance tuning method of allowing faster retrieval of records from the
table. An index creates an entry for each value and hence it will be faster to retrieve data.
A NULL value is not at all same as that of zero or a blank space. NULL value represents a value
which is unavailable, unknown, assigned or not applicable whereas a zero is a number and blank
space is a character.
The cross join produces the cross product or Cartesian product of two tables whereas the natural
join is based on all the columns having the same name and data types in both the tables.
What is subquery in SQL?
A subquery is a query inside another query where a query is defined to retrieve data or
information back from the database. In a subquery, the outer query is called as the main query
whereas the inner query is called subquery. Subqueries are always executed first and the result of
the subquery is passed on to the main query. It can be nested inside a SELECT, UPDATE or any
other query. A subquery can also use any comparison operators such as >,< or =.
Correlated subquery: These are queries which select the data from a table referenced in the outer
query. It is not considered as an independent query as it refers to another table and refers the
column in a table.
Non-Correlated subquery: This query is an independent query where the output of subquery is
substituted in the main query.
Aggregate functions are used to evaluate mathematical calculation and returns a single value.
These calculations are done from the columns in a table. For example- max(),count() are
calculated with respect to numeric.
Scalar functions return a single value based on the input value. For example – UCASE(), NOW()
are calculated with respect to string.
You can fetch alternate records i.e both odd and even row numbers. For example- To display
even numbers, use the following command:
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=0
Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1
= is used to assign one value or variable to another variable. == is used for comparing two strings
or numbers. === is used to compare only string with the string and number with numbers.
Web Service
WCF
WCF Rest
Web API
This is the new framework for building HTTP services with easy and simple way.
Web API is open source an ideal platform for building REST-ful services over the .NET
Framework.
Unlike WCF Rest service, it use the full feature of HTTP (like URIs, request/response headers,
caching, versioning, various content formats)
It also supports the MVC features such as routing, controllers, action results, filter, model
binders, IOC container or dependency injection, unit testing that makes it more simple and
robust.
It can be hosted with in the application or on IIS.
It is light weight architecture and good for devices which have limited bandwidth like smart
phones.
Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever
format you want to add as a MediaTypeFormatter.
To whom choose between WCF or WEB API
Choose WCF when you want to create a service that should support special scenarios such as one
way messaging, message queues, duplex communication etc.
Choose WCF when you want to create a service that can use fast transport channels when
available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to
support HTTP when all other transport channels are unavailable.
Choose Web API when you want to create a resource-oriented services over HTTP that can use
the full features of HTTP (like URIs, request/response headers, caching, versioning, various
content formats).
Choose Web API when you want to expose your service to a broad range of clients including
browsers, mobiles, iphone and tablets.