0% found this document useful (0 votes)
9 views58 pages

Important Topics

The document provides various SQL and programming concepts, including methods for deleting duplicate data from a table, differences between synchronous and asynchronous AJAX requests, and distinctions between float and decimal data types. It also covers the Model-View-Controller (MVC) architecture, its advantages, application life cycle, routing, action filters, and various data passing techniques in ASP.NET MVC. Additionally, it discusses HTML helpers, Razor view engine, forms authentication, areas in MVC, display modes, and scaffolding in ASP.NET applications.

Uploaded by

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

Important Topics

The document provides various SQL and programming concepts, including methods for deleting duplicate data from a table, differences between synchronous and asynchronous AJAX requests, and distinctions between float and decimal data types. It also covers the Model-View-Controller (MVC) architecture, its advantages, application life cycle, routing, action filters, and various data passing techniques in ASP.NET MVC. Additionally, it discusses HTML helpers, Razor view engine, forms authentication, areas in MVC, display modes, and scaffolding in ASP.NET applications.

Uploaded by

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

-------------------------- Delete Duplicate Data from Table -- Start

• Having and Group By

delete from EmpDup where EmpID in(select EmpID from EmpDup group by EmpId having
count(*) >1)

• With CTE

With CTE_Duplicates as

(select empid, row_number() over(partition by empid order by empid) rownumber

from EmpDup )

delete from CTE_Duplicates where rownumber!=1

-------------------------- Delete Duplicate Data from Table -- End

--------------- Difference Between Synchronous and Asynchronous in Ajax -- Start

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.

Asynchronous (AJAX Web-Application Model) : An asynchronous request doesn’t block the


client i.e. browser is responsive. At that time, user can perform another operations also. In such
case, javascript engine of the browser is not blocked.
by default async is true. it means process will be continuing in jQuery ajax without wait of
request.Async false means it will not go to next step untill the response will come

--------------- Difference Between Synchronous and Asynchronous in Ajax -- End

--------------- Difference Between Float and decimal -- Start

Decimal : A Decimal number contains upto 38 digits. It contains 5 to 17 bytes depending on


precision.

Float : Float contains 4 bytes depending on precision.

--------------- Difference Between Float and decimal -- End

--------------------- MVC Start---

ASP.Net MVC

1. What is MVC (Model view controller)?


Model–view–controller (MVC) is a software architectural pattern for implementing user
interfaces. It divides a given software application into three interconnected parts, so as to
separate internal representation of information from the way that information is presented to or
accepted from the user.
MVC is a framework for building web applications using a MVC (Model View Controller) design:
• Model is the part of the application that handles the logic for the application data,
represents the application core (for instance a list of database records).
• View is the part of the application that handles the display of the data. Most often the
views are created from the model data.
• The Controller is the part of the application that handles user interaction. Typically
controllers read data from a view, control user input, and send input data to the model.
The MVC model also provides full control over HTML, CSS, and JavaScript.

2. What are the advantages of 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.

Separation of Concerns - Separation of Concerns is one of the core advantages of ASP.NET


MVC . The MVC framework provides a clean separation of the UI, Business Logic, Model or
Data.

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.

3. Explain MVC application life cycle?


MVC has two life cycles −

• The application life cycle


• The request life cycle

• The Application Life Cycle


The application life cycle refers to the time at which the application process actually begins running
IIS until the time it stops. This is marked by the application start and end events in the startup file
of your application.

• The Request Life Cycle

4. List out different return types of a controller action method?


The base type of all result types is ActionResult. They are:
• ViewResult (View): This return type is used to return a webpage from an action method.
• PartialviewResult (Partialview): This return type is used to send a part of a view which
will be rendered in another view.
• RedirectResult (Redirect): This return type is used to redirect to any other controller
and action method depending on the URL.
• RedirectToRouteResult (RedirectToAction, RedirectToRoute): This return type is used
when we want to redirect to any other action method.
• ContentResult (Content): This return type is used to return HTTP content type like
text/plain as the result of the action.
• jsonResult (json): This return type is used when we want to return a JSON message.
• javascriptResult (javascript): This return type is used to return JavaScript code that will
run in browser.
• FileResult (File): This return type is used to send binary output in response.
• EmptyResult: This return type is used to return nothing (void) in the result.

5. What are Filters in MVC?

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.

ASP.NET MVC framework supports the following action filters:


• Action Filters: Action filters are used to implement logic that gets executed before and
after a controller action executes. We will look at Action Filters in detail in this chapter.
• Authorization Filters: Authorization filters are used to implement authentication and
authorization for controller actions.
• Result Filters: Result filters contain logic that is executed before and after a view result
is executed. For example, you might want to modify a view result right before the view is
rendered to the browser.
• Exception Filters: Exception filters are the last type of filter to run. You can use an
exception filter to handle errors raised by either your controller actions or controller
action results. You can also use exception filters to log errors.

6. What are Action Filters in MVC?

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.

A call to set up convention-based routes might look like this:


Let's break down some of the pieces here:

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

• A call to MapRoute allows us to add a route to the route table

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.

Enable Attribute Routing

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

8.What is Route in MVC? What is Default Route in MVC?

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

10. What is Partial View in MVC?

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.

12. Explain attribute based routing in MVC?

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

public class HomeController: Controller


{
[Route("Users/about")]
Public ActionResult GotoAbout()
{
return View();
}
}
13. What are HTML helpers in MVC?

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.

14. What is Razor in MVC?

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?

• Compact & Expressive.


• Razor minimizes the number of characters and keystrokes required in a file, and enables
a fast coding workflow. Unlike most template syntaxes, you do not need to interrupt your
coding to explicitly denote server blocks within your HTML. The parser is smart enough
to infer this from your code. This enables a really compact and expressive syntax which
is clean, fast and fun to type.
• Easy to Learn: Razor is easy to learn and enables you to quickly be productive with a
minimum of effort. We can use all your existing language and HTML skills.
• Works with any Text Editor: Razor doesn't require a specific tool and enables you to be
productive in any plain old text editor (notepad works great).
• Has great Intellisense:
• Unit Testable: The new view engine implementation will support the ability to unit test
views (without requiring a controller or web-server, and can be hosted in any unit test
project - no special app-domain required).

15. How do you implement Forms authentication in MVC?

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>

The FormsAuthentication class creates the authentication cookie automatically when


SetAuthCookie() or RedirectFromLoginPage() methods are called. The value of authentication
cookie contains a string representation of the encrypted and signed FormsAuthenticationTicket
object.

16. Explain Areas in MVC?

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

Benefits of Area in MVC:


• Allows us to organize models, views and controllers into separate functional sections of
the application, such as administration, billing, customer support and much more.
• Easy to integrate with other Areas created by another.
• Easy for unit testing.

17. Explain the need of display mode in MVC?

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.

19. What is Route Constraints in MVC?

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:

20. What is Output Caching in MVC?

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.

21. What is Bundling and Minification in MVC?

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.

22. What is difference between MVC and Web Forms?

ASP.Net MVC ASP.Net Web Forms


View and logic are separate, it has
separation of concerns theory. MVC 3 No separation of concerns; Views are tightly
onwards has .aspx page as .cshtml. coupled with logic (.aspx.cs /.vb file).
Introduced concept of routing for route based
URL. Routing is declared in Global.asax for File-based routing .Redirection is based on
example. pages.
Support Razor syntax as well as .aspx Support web forms syntax only.
State management handled via Tempdata,
ViewBag, and View Data. Since the
controller and view are not dependent and State management handled via View State.
also since there is no view state concept in Large viewstate, in other words increase in
ASP.NET, MVC keeps the pages lightweight. page size.
Partial Views User Controls
HTML Helpers Server Controls
Multiple pages can have the same controller Each page has its own code, in other words
to satisfy their requirements. A controller may direct dependency on code. For example
have multiple Actions (method name inside Sachin.aspx is dependent on Sachin.aspx.cs
the controller class). (code behind) file.
Unit Testing is quite easier than ASP.Net
Web forms Since a web form and code are Direct dependency, tight coupling raises
separate files. issues in testing.
layouts Master pages

23. What is Validation Summary in MVC?

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.

24. What are the methods of handling an Error in MVC?

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

HandleError Attribute at Action Method Level,


[HandleError(View = "Error")]
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
int u = Convert.ToInt32(""); // Error line
return View();
}

25. What is ViewStart?

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.

26. What is Data Annotation Validator Attributes in MVC?

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

27. How can we implement Custom Error Page in MVC?

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>

Then, your action method needs to be marked with the atttribute.

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

29. Explain Sections in MVC?


Section are the part of HTML which is to be rendered in layout page. In Layout page we will use
the below syntax for rendering the HTML –

@RenderSection(“TestSection”)

And in child pages we are defining these sections as shown below –

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

30. What are Non Action methods in MVC?

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
}

31. Can you explain RenderBody and RenderPage in MVC?

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.

32. What is Html.RenderPartial?

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

33. Model Binding in MVC?

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.

Binding to Complex type


Model binding in MVC framework automatically converts form field data of HttpPOST request to
the properties of a complex type parameter of an action method.

34. What is the “HelperPage.IsAjax” Property?


The HelperPage.IsAjax property gets a value that indicates whether Ajax is being used during
the request of the Web page.

35. Why to use Html.Partial in MVC?

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

36. Difference between MVC3, MVC4 and MVC5:

--------------------- MVC End---

--------------------- JQuery Start---

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.

• Cross-browser support and detection.


• AJAX functions
• CSS functions
• DOM manipulation
• DOM transversal
• Attribute manipulation
• Event detection and handling.
• JavaScript animation
• Hundreds of plugins for pre-built user interfaces, advanced animations, form validation,
etc.
• Expandable functionality using custom plugins.

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.

Need For a CDN

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.

We can rewrite $(document).ready() as jQuery (document).ready(), since $ is an alias for jQuery.


Always use jQuery in place of $, if you are using more than one JavaScript library to resolve
conflicts with jQuery library. The methods called on $(), will implicitly be applied on all the
elements returned by it without need of explicit looping. Let's say, $('.myclass').hide() will hide
all elements with class as myclass with implicit looping.

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.

5. What is the use of jQuery .each() function?

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

var arr = ["Goergie", "Johnson", "Agile", "Harrison", "Gaurav"];

$.each(arr, function (index, value) {

alert('Position is : '+ index + ' And Value is : ' + value);

});

});

</script>

Output :
Position is : 1 And Value is : Goergie

Position is : 2 And Value is : Johnson

Position is : 3 And Value is : Harrison

Position is : 4 And Value is : Gaurav

6. What is difference between prop and attr?

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.

What Attributes actually are


Attributes carry additional information about an HTML element and come in name=”value”
pairs. You can set an attribute for an HTML element and define it when writing the source code.

For example

<input id="txtBox" value="Jquery" type="text" readonly="readonly" />

As shown above, “id”, "type” and “value" are attributes of the input elements.

7. What is jQuery UI?

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

8. What is the difference between $(window).load and $(document).ready function in


jQuery?

$(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.

<script type="text/javascript" lang="ja">

$(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.

The document ready function will be fired first.

Then the window load event will be fired.

When to use $(window).load instead of $(document).ready

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.

10. What is chaining in jQuery?

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.

By using chaining we can write the above code as follows:


$(document).ready(function() {

$("#div2").html($("#txtBox").prop("readonly")) + '</br>';

$("#div3").html($("#txtBox").attr("readonly"));

});
The code segment above is described by the following image:

11. What is Ajax in jQuery?


AJAX stands for “Asynchronous JavaScript and XML”. AJAX is about exchanging data with a
server, without reloading the whole page. It is a technique for creating fast and dynamic web
pages.

In .NET, we can call server side code using two ways:


ASP .NET AJAX
jQuery AJAX
In this article we will focus on jQuery Ajax.

$.ajax () Method

JQuery’s core method for creating Ajax requests. Here are some jQuery AJAX methods:

$.ajax() - Performs an async AJAX request.


$.get() - Loads data from a server using an AJAX HTTP GET request.
$.post() - Loads data from a server using an AJAX HTTP POST request.
To know more click.

$.ajax () Method Configuration option

Options that we use:

async
type
url
data
datatype
success
error
Let’s have a detailed overview:

async

Set to false if the request should be sent synchronously. Defaults to true.

12. What is the use of jQuery filter?

JQuery supports various types of filters, such as:


.eq()
.first()
.last()
.filter()
.has()
.not()
13. What is the use of jQuery.ajax method()?

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.

--------------------- JQuery End---

--------------------- Web Api Start---

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) Explain Web API Routing?

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}

defaults: new { id = RouteParameter.Optional}


};

4) List out the differences between WCF and Web API?

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.

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

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

7) List out differences between MVC and Web API?

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.

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

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

10) Can we return view from Web API?

No. We cannot return view from Web API.

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

12) Can we use Web API with ASP.NET Web Forms?

Yes. We can use Web API with ASP.NET Webforms.

13) 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 asax
Make a AJAX call to Web API actions.

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.

16) Explain Exception Filters?

Exception filters will be executed whenever controller methods (actions) throws an exception
which is unhandled. Exception filters will implement “IExceptionFilter” interface.

17) How can we pass multiple complex types in Web API?

Below are the methods to pass the complex types in Web API –

• Using ArrayList
• Newtonsoft JArray

18) Write a code snippet for passing arraylist in Web API?

Below is the code snippet for passing arraylist –

ArrayList paramList = new ArrayList();

Category c = new Category { CategoryId = 1, CategoryName = “SmartPhones”};

Product p = new Product { ProductId = 1, Name = “Iphone”, Price = 500, CategoryID = 1


};

paramList.Add(c);
paramList.Add(p);

19) Give an example of Web API Routing?

Below is the sample code snippet to show Web API Routing –

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

20) How we can handle errors in Web API?

Below are the list of classes which can be used for error handling –

• HttpResponseException
• Exception Filters
• Registering Exception Filters
• HttpError

21) Explain how we can handle error from “HttpResponseException”?

This returns the HTTP status code what you specify in the constructor. Eg :

public TestClass MyTestAction(int id)


{
TestClass c = repository.Get(id);
if (c == null)
{
throw new HttpResponseException(HttpStatusCode.NotFound);
}
return c;
}

22) How to register Web API exception filters?

Below are the options to register Web API exception filters –

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

24) Write a code snippet to register exception filters from controller?

Below is the code snippet for registering exception filters from controller –

[NotImplExceptionFilter]
public class TestCustomerController : Controller
{
//Your code goes here
}

25) How to handle error using HttpError?

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 –

string message = string.Format(“TestCustomer id = {0} not found”, customerid);

return Request.CreateErrorResponse(HttpStatusCode.NotFound, message);

27) How to enable tracing in Web API?

To enable tracing place below code in –“Register” method of WebAPIConfig.cs file.

config.EnableSystemDiagnosticsTracing();

28) Explain Authentication in Web API?


Web API authentication will happen in host. In case of IIS it uses Http Modules for
authentication or we can write custom Http Modules. When host is used for authentication it
used to create principal, which represent security context of the application.

29) What are media types?

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.

30) List out few media types of HTTP?

Below are the list of media types –

• Image/Png
• Text/HTML
• Application/Json

31) Explain Media Formatters in Web API?

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.

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

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

34) Give an example of creating custom action filter in Web API?

Below is the sample code for creating custom action filter –

public class MyCustomModelAttribute : ActionFilterAttribute


{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
//Code goes here
}
}
}

In case validation fails here it returns HTTP response which contains validation errors.

35) How to apply custom action filter in WebAPI.config?

Add a new action filter in “Register” method as shown –

public static class WebApiConfig


{
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new MyCustomModelAttribute());
// …
}
}

--------------------- Web Api End---

--------------------- Sql Server Start---

In what sequence SQL statement are processed?

The clauses of the select are processed in the following sequence

• FROM clause
• WHERE clause
• GROUP BY clause
• HAVING clause
• SELECT clause
• ORDER BY clause
• TOP clause

What are different types of statements supported by SQL?


• DDL (Data Definition Language): It is used to define the database structure such as
tables. It includes three statements such as Create, Alter, and Drop.

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

There are 5 major constraints are used in SQL, such as

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

What are transaction and its controls?


A transaction can be defined as the sequence task that is performed on databases in a logical
manner to gain certain results. Operations performed like Creating, updating, deleting records in
the database comes from transactions.

In simple word, we can say that a transaction means a group of SQL queries executed on
database records.

There are 4 transaction controls such as

COMMIT: It is used to save all changes made through the transaction


ROLLBACK: It is used to roll back the transaction such as all changes made by the transaction
are reverted back and database remains as before
SET TRANSACTION: Set the name of transaction
SAVEPOINT: It is used to set the point from where the transaction is to be rolled back.

What are properties of the transaction?

Properties of transaction are known as ACID properties, such as

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.

How many Aggregate Functions are available there in SQL?

SQL Aggregate Functions calculates values from multiple columns in a table and returns a single
value.

There are 7 aggregate functions we use in SQL

AVG(): Returns the average value from specified columns


COUNT(): Returns number of table rows
MAX(): Returns largest value among the records
MIN(): Returns smallest value among the records
SUM(): Returns the sum of specified column values
FIRST(): Returns the first value
LAST(): Returns Last value.
What are Scalar Functions in SQL?

Scalar Functions are used to return a single value based on the input values. Scalar Functions are
as follows

UCASE(): Converts the specified field in upper case


LCASE(): Converts the specified field in lower case
MID(): Extracts and returns character from text field
FORMAT(): Specifies the display format
LEN(): Specifies the length of text field
ROUND(): Rounds up the decimal field value to a number.

What are triggers?

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.

Syntax: CREATE TRIGGER name {BEFORE|AFTER} (event [OR..]}


ON table_name [FOR [EACH] {ROW|STATEMENT}]
EXECUTE PROCEDURE functionname {arguments}

What is View in SQL?

A View can be defined as a virtual table that contains rows and columns with fields from one or
more table.

Syntax: CREATE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

How we can update the view?

SQL CREATE and REPLACE can be used for updating the view.

Following query syntax is to be executed to update the created view

Syntax: CREATE OR REPLACE VIEW view_name AS


SELECT column_name(s)
FROM table_name
WHERE condition

Explain the working of SQL Privileges?

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.

Syntax: GRANT privilege_name


ON object_name
TO {user_name|PUBLIC|role_name}
[WITH GRANT OPTION];

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.

Syntax: REVOKE privilege_name


ON object_name
FROM {user_name|PUBLIC|role_name};

What is SQL Injection?

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.

For Example: SELECT column_name(s) FROM table_name WHERE condition;

What is the use of NVL function?

NVL function is used to convert the null value to its actual value.

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

What are the different types of a subquery?

There are two types of subquery namely, Correlated and Non-Correlated.

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.

What is the difference between clustered and non-clustered indexes?

• 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

What is the difference between DELETE and TRUNCATE?

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

What is the difference between DROP and TRUNCATE?

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.

What is Normalization? How many Normalization forms are there?

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.

There are 5 forms of Normalization


First Normal Form (1NF): It removes all duplicate columns from the table. Creates a table for
related data and identifies unique column values
First Normal Form (2NF): Follows 1NF and creates and places data subsets in an individual
table and defines the relationship between tables using the primary key
Third Normal Form (3NF): Follows 2NF and removes those columns which are not related
through primary key
Fourth Normal Form (4NF): Follows 3NF and do not define multi-valued dependencies. 4NF
also known as BCNF.

What do you mean by Denormalization?

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.

What is Relationship? How many types of Relationship are there?

The relationship can be defined as the connection between more than one tables in the database.

There are 4 types of relationships

• One to One Relationship


• Many to One Relationship
• Many to Many Relationship
• One to Many Relationship

What do you mean by Stored Procedures? How do we use it?

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.

Syntax: CREATE Procedure Procedure_Name


(
//Parameters
)
AS
BEGIN
SQL statements in stored procedures to update/retrieve records
END

What is a Cursor?
A cursor is a database object which is used to manipulate data in a row-to-row manner.

Cursor follows steps as given below

• Declare Cursor
• Open Cursor
• Retrieve row from the Cursor
• Process the row
• Close Cursor
• Deallocate Cursor

What are Indexes in SQL?

The index can be defined as the way to retrieve the data more quickly. We can define indexes
using CREATE statements.

Syntax: CREATE INDEX index_name


ON table_name (column_name)

Further, we can also create Unique Index using following syntax;

Syntax: CREATE UNIQUE INDEX index_name


ON table_name (column_name)

Which TCP/IP port does SQL Server run?

By default SQL Server runs on port 1433.

Define a temp table?

A temp table is a temporary storage structure to store the data temporarily.

What is the difference between CHAR and VARCHAR2 datatype in SQL?

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;

What is the need of MERGE statement?

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.

What is the difference between ‘HAVING’ CLAUSE and a ‘WHERE’ CLAUSE?

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.

What are aggregate and scalar functions?

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.

How can you fetch first 5 characters of the string?

There are a lot of ways to fetch characters from a string. For example:

Select SUBSTRING(StudentName,1,5) as studentname from student.

What are Local and Global variables?

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.

What are STUFF and REPLACE function?

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

--------------------- Angular JS Start---

What is the difference between Angular and jQuery?

Features jQuery Angular


DOM Manipulation Yes Yes
RESTful API No Yes
Animation Support Yes Yes
Deep Linking RoutingNo Yes
Form Validation No Yes
2 Way Data Binding No Yes
AJAX/JSONP Yes Yes

Name the key features of AngularJS?

The key features of AngularJS are:

• Scope
• Controller
• Model
• View
• Services
• Data Binding
• Directives
• Filters
• Testable

Explain data binding in AngularJS.

According to AngularJS.org, “Data-binding in Angular apps is the automatic synchronization of


data between the model and view components. The way that Angular implements data-binding
lets you treat the model as the single-source-of-truth in your application. The view is a projection
of the model at all times. When the model changes, the view reflects the change and vice versa.”

There are two ways of data binding:

• Data mining in classical template systems


• Data binding in angular templates

What are directives in AngularJS?

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.

The different types of directives are:

• Element directives
• Attribute directives
• CSS class directives
• Comment directives

What are Controllers in AngularJS?

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

What is the difference between link and compile in Angular.js?

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.

What are the characteristics of ‘Scope’?

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 ($watch) to observe model mutations.

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

What are the advantages of using Angular.js framework?

Angular.js framework has the following advantages:

• Supports two way data-binding


• Supports MVC pattern
• Support static template and angular template
• Can add custom directive
• Supports REST full services
• Supports form validations
• Support both client and server communication
• Support dependency injection
• Applying Animations
• Event Handlers

What is the difference between AngularJS and backbone.js?

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.

Explain what is injector in AngularJS?

An injector is a service locator, used to retrieve object instance as defined by provider, instantiate
types, invoke methods, and load modules.

What is factory method in AngularJS?

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.

Syntax: module.factory( 'factoryName', function );

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.

What is ng-app, ng-init and ng-model?

• ng-app : Initializes application.


• ng-model : Binds HTML controls to application data.
• ng-Controller : Attaches a controller class to view.
• ng-repeat : Bind repeated data HTML elements. Its like a for loop.
• ng-if : Bind HTML elements with condition.
• ng-show : Used to show the HTML elements.
• ng-hide : Used to hide the HTML elements.
• ng-class : Used to assign CSS class.
• ng-src : Used to pass the URL image etc.

Does Angular use the jQuery library?


Yes, Angular can use jQuery if it’s present in the app when the application is being bootstrapped.
If jQuery is not present in the script path, Angular falls back to its own implementation of the
subset of jQuery that we call jQLite.

Can AngularJS have multiple ng-app directives in a single page?

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.

Can angular applications (ng-app) be nested within each other?


No. AngularJS applications cannot be nested within each other.

What is internationalization and how to implement it in AngularJS?

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.

On which types of component can we create a custom directive?

AngularJS provides support to create custom directives for the following:

• Element directives − Directive activates when a matching element is encountered.


• Attribute − Directive activates when a matching attribute is encountered.
• CSS − Directive activates when a matching css style is encountered.
• Comment − Directive activates when a matching comment is encountered.

What is $rootscope in AngularJS?

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.

Can we have nested controllers in AngularJS?

Yes, we can create nested controllers in AngularJS. Nested controllers are defined in hierarchical
manner while using in View.

What is bootstrapping in AngularJS?

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:

• MVC implementation is done right.


• It extends HTML using directives, expression and data binding techniques to define a
powerful HTML template.
• Two way data-binding, form validations, routing supports, inbuilt services.
• REST friendly.
• Dependency injection support.
• It helps you to structure and test your JavaScript code.

Is AngularJS compatible with all browsers?

Yes AngularJS is compatible with the following browsers: Safari, Chrome, Firefox, Opera 15,
IE9 and mobile browsers (Android, Chrome Mobile, iOS Safari).

How to implement routing in AngularJS?

It is a five-step process:

Step 1: – Add the “Angular-route.js” file to your view.


Step 2: – Inject “ngroute” functionality while creating Angular app object.
Step 3: – Configure the route provider.
Step 4: – Define hyperlinks.
Step 5: – Define sections where to load the view.

Explain $q service, deferred and promises.

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

--------------------- Angular JS End---

Lazy Loading In C# 4.0 (Object On Demand)

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;

Difference Between Abstraction and Encapsulation


Order of execution of a SQL Query

SELECT DISTINCT column, AGG_FUNC(column_or_expression), …


FROM mytable
JOIN another_table
ON mytable.column = another_table.column
WHERE constraint_expression
GROUP BY column
HAVING constraint_expression
ORDER BY column ASC/DESC
LIMIT count OFFSET COUNT;

Query order of execution

1. FROM and JOINs

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

--all possible parents of @id is already given

DECLARE @id BIGINT;


SET @id = 5;
WITH tblParent AS
(
SELECT *
FROM UserType WHERE Id = @id
UNION ALL
SELECT UserType.*
FROM UserType JOIN tblParent ON UserType.Id = tblParent.ParentId
)
SELECT * FROM tblParent
WHERE Id <> @id
OPTION(MAXRECURSION 32767)

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.

There are 5 major constraints are used in SQL, such as

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

What port does SQL server run on?

1433 is the standard port for SQL server.


What is the SQL CASE statement used for? Explain with an example?

SELECT Employee_Name, CASE Location


WHEN 'alex' THEN Bonus * 2
WHEN 'robin' THEN Bonus *, 5
ELSE Bonus
END
"New Bonus"
FROM Intellipaat_employee;

What is the difference between CHAR and VARCHAR2 datatype in SQL?

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.

Are NULL values same as that of zero or a blank space?

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.

What is the difference between cross join and natural join?

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

What are the different types of a subquery?

There are two types of subquery namely, Correlated and Non-Correlated.

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.

What are aggregate and scalar functions?

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.

How can you fetch alternate records from a table?

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

Now, to display odd numbers:

Select studentId from (Select rowno, studentId from student) where mod(rowno,2)=1

What is the use of =,==,=== operators?

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

Difference Between Web Service , WCF , WCF Rest , Web API


The .Net framework has a number of technologies that allow you to create HTTP services such
as Web Service, WCF and now Web API. There are a lot of articles over the internet which may
describe to whom you should use.

Web Service

It is based on SOAP and return data in XML form.


It support only HTTP protocol.
It is not open source but can be consumed by any client that understands xml.
It can be hosted only on IIS.

WCF

It is also based on SOAP and return data in XML form.


It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP,
HTTPS, Named Pipes, MSMQ.
The main issue with WCF is, its tedious and extensive configuration.
It is not open source but can be consumed by any client that understands xml.
It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

To use WCF as WCF Rest service you have to enable webHttpBindings.


It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
To enable other HTTP verbs you have to do some configuration in IIS to accept request of that
particular verb on .svc files
Passing data through parameters using a WebGet needs configuration. The UriTemplate must be
specified.
It support XML, JSON and ATOM data format.

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.

You might also like