React: 'P' 'This Is A Text' 'Div' ' '
React: 'P' 'This Is A Text' 'Div' ' '
React: 'P' 'This Is A Text' 'Div' ' '
2. What is JSX?
JSX stands for JavaScript XML.
It allows us to write HTML inside JavaScript and place them in the DOM without using functions like
appendChild( ) or createElement( ).
As stated in the official docs of React, JSX provides syntactic sugar for React.createElement( ) function.
**Note- We can create react applications without using JSX as well.
Let’s understand how JSX works:
Without using JSX, we would have to create an element by the following process:
const text = React.createElement('p', {}, 'This is a text');
const container = React.createElement('div','{}',text );
ReactDOM.render(container,rootElement);
Using JSX, the above code can be simplified:
const container = (
<div>
<p>This is a text</p>
</div>
);
ReactDOM.render(container,rootElement);
As one can see in the code above, we are directly using HTML inside JavaScript.
Decalaration
Functional components are nothing but JavaScript functions and therefore can be declared using
an arrow function or the function keyword:
function card(props){
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
const card = (props) =>{
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
Class components on the other hand, are declared using the ES6 class:
class Card extends React.Component{
constructor(props){
super(props);
}
render(){
return(
<div className="main-container">
<h2>Title of the card</h2>
</div>
)
}
}
Handling props
Let’s render the following component with props and analyse how functional and class components
handle props:
<StudentInfo name="Vivek" rollNumber="23" />
In functional components, the handling of props is pretty straight forward. Any prop provided as an
argument to a functional component, can be directly used inside HTML elements:
function StudentInfo(props){
return(
<div className="main">
<h2>{props.name}</h2>
<h4>{props.rollNumber}</h4>
</div>
)
}
render(){
return(
<div className="main">
<h2>{this.props.name}</h2>
<h4>{this.props.rollNumber}</h4>
</div>
)
}
}
As we can see in the code above, this keyword is used in the case of class components.
Handling state
Functional components use React hooks to handle state.
It uses the useState hook to set state of a variable inside the component:
function ClassRoom(props){
let [studentsCount,setStudentsCount] = useState(0);
const addStudent = () => {
setStudentsCount(++studentsCount);
}
return(
<div>
<p>Number of students in class room: {studentsCount}</p>
<button onClick={addStudent}>Add Student</button>
</div>
)
}
4. What is the virtual DOM? How does react use the virtual DOM to render the UI?
As stated by the react team, virtual DOM is a concept where a virtual representation of the real DOM is
kept inside the memory and is synced with the real DOM by a library such as ReactDOM.
Why was virtual DOM introduced? DOM manipulation is an integral part of any web application, but
DOM manipulation is quite slow when compared to other operations in JavaScript.
The efficiency of the application gets affected when several DOM manipulations are being done. Most
JavaScript frameworks update the entire DOM even when a small part of the DOM changes.
For example, consider a list that is being rendered inside the DOM. If one of the items in the list
changes, the entire list gets rendered again instead of just rendering the item that was
changed/updated. This is called inefficient updating.
To address the problem of inefficient updating, the react team introduced the concept of virtual DOM.
For every DOM object, there is a corresponding virtual DOM object(copy), which has the same properties.
The main difference between the real DOM object and the virtual DOM object is that any changes in the virtual DOM object will not reflect on the
screen directly. Consider a virtual DOM object as a blueprint of the real DOM object.
Whenever a JSX element gets rendered, every virtual DOM object gets updated.
**Note- One may think updating every virtual DOM object might be inefficient, but that’s not the case. Updating the virtual DOM is much
faster than updating the real DOM since we are just updating the blueprint of the real DOM.
React uses two virtual DOMs to render the user interface. One of them is used to store the current state of the objects and the other to store the
previous state of the objects.
Whenever the virtual DOM gets updated, react compares the two virtual DOMs and gets to know about which virtual DOM objects were updated.
After knowing which objects were updated, react renders only those objects inside the real DOM instead of rendering the complete real DOM.
This way, with the use of virtual DOM, react solves the problem of inefficient updating.
Controlled component In a controlled component, the value of the input element is controlled by React.
We store the state of the input element inside the code, and by using event-based callbacks, any
changes made to the input element will be reflected in the code as well.
When a user enters data inside the input element of a controlled component, onChange function gets
triggered and inside the code we check whether the value entered is valid or invalid. If the value is valid,
we change the state and re-render the input element with new value.
Example of a controlled component:
function FormValidation(props) {
let [inputValue, setInputValue] = useState("");
return (
<div>
<form>
<input type="text" value={inputValue} onChange={updateInput} />
</form>
</div>
);
}
As one can see in the code above, the value of the input element is determined by the state of
the inputValue variable. Any changes made to the input element is handled by
the updateInput function.
Uncontrolled component In an uncontrolled component, the value of the input element is handled by
the DOM itself.
Input elements inside uncontrolled components work just like normal HTML input form elements.
The state of the input element is handled by the DOM. Whenever the value of the input element is
changed,event-based callbacks are not called. Basically, react does not perform any action when there
are changes made to the input element.
Whenever use enters data inside the input field, the updated data is shown directly. To access the value
of the input element, we can use ref.
Example of an uncontrolled component:
function FormValidation(props) {
let inputValue = React.createRef();
return (
<div>
<form onSubmit={handleSubmit}>
<input type="text" ref={inputValue} />
<button type="submit">Submit</button>
</form>
</div>
);
}
As one can see in the code above, we are not using onChange function to govern the changes made to the input element. Instead, we are using ref to
access the value of the input element.
**Note- In this article, we are discussing the use of lifecycle methods in class components. For utilising
lifecycle methods in functional components, react hooks are used.
Mounting:
There are four built-in lifecycle methods that are called in the following order when a component is mounted:
constructor( ) - This is called before anything else. We can set the initial state of the component inside this method. The constructor method is used to
set the initial state and bind methods to the component.
getDerivedStateFromProps( ) - This is called before rendering the elements in the DOM.
In this method, we can set the state of the component based on the props we received. This method is used very rarely.
render( ) - This is the only required method in the class component. This method returns the HTML elements which are going to be rendered inside the
DOM.
componentDidMount( ) - It is called right after the component is rendered inside the DOM. All the statements which require the DOM nodes can be
executed in this method. Network requests from a remote end-point can also be instantiated in this method.
Updating:
Updates in react are caused by changes in state or props. Update leads to re-rendering of the component. The following methods are called when a
component is re-rendered:
getDerivedStateFromProps( ) - This method is called again when a component is being re-rendered.
shouldComponentUpdate( ) - This method is called before rendering the component when new props are received. It lets React know if the
component’s output is affected by the newly received props or by the state change. By default, it returns true.
render( ) - To re-render the HTML inside the DOM, the render( ) method gets called again.
getSnapshotBeforeUpdate( ) - This method is called just before the newly rendered HTML gets committed to the DOM. It stores the previous state of
the component so that React has an idea of what parts of the DOM needs to be updated.
componentDidUpdate( ) - It is called after the component gets re-rendered. This method works just like the componentDidMount( ) method, the
difference is that this method does not get called on initial render.
Unmounting:
componentWillUnmount( ) - This method is called just before the component gets destroyed. Any clean up statements should be executed inside this
method.
StrictMode is a tool added in the version 16.3 of React to highlight potential problems in an application.
It performs additional checks on the application.
function App() {
return (
<React.StrictMode>
<div classname="App">
<Header/>
<div>
Page Content
</div>
<Footer/>
</div>
</React.StrictMode>
);
}
render() {
console.log("Parent is getting rendered" );
return (
<div className="App">
<Message />
</div>
);
}
}
Parent component is the parent component and Message is the child component. Any change in the
parent component will lead to re-rendering of the child component as well.
To prevent the re-rendering of child component, we use the shouldComponentUpdate( ) method:
**Note- Use shouldComponentUpdate( ) method only when you are sure that it’s a static component.
class Message extends React.Component {
constructor(props) {
super(props);
this.state = { message: "Hello, this is vivek" };
}
shouldComponentUpdate() {
console.log("Does not get rendered");
return false;
}
render() {
console.log("Message is getting rendered");
return (
<div>
<p>{this.state.message}</p>
</div>
);
}
}
As one can see in the code above, we have returned false from the shouldComponentUpdate( ) method, which prevents the child component from re-
rendering.
React State
Every component in react has a built-in state object, which contains all the property values that belong
to that component.
In other words, the state object controls the behaviour of a component. Any change in the property
values of the state object leads to re-rendering of the component.
**Note- State object is not available in functional components but, we can use React Hooks to add
state to a functional component.
changeColor() {
this.setState(prevState => {
return { color: "Red" };
});
}
render() {
return (
<div>
<button onClick={() => this.changeColor()}>Change Color</button>
<p>{this.state.color}</p>
</div>
);
}
}
As one can see in the code above, we can use the state by calling this.state.propertyName and we can change the state object property
using setState method.
React Props
Every react component, accepts a single object argument called props (which stands for “properties”).
These props can be passed to a component using HTML attributes and the component accepts these props as an argument.
Using props, we can pass data from one component to another.
Passing props to a component:
While rendering a component, we can pass the props as a HTML attribute:
<Car brand="Mercedes"/>
In Functional component:
function Car(props) {
let [brand, setBrand] = useState(props.brand);
}
****Note- Props are read-only. They cannot be manipulated or changed inside a component.
The state variable “name” can be directly used inside the HTML.
CSS Stylesheet
We can create a separate CSS file and write all the styles for the component inside that file. This file
needs to be imported inside the component file.
import './RandomComponent.css';
class RandomComponent extends React.Component {
render() {
return (
<div>
<h3 className="heading">This is a heading</h3>
<p className="paragraph">This is a paragraph</p>
</div>
);
}
}
CSS Modules
We can create a separate CSS module and import this module inside our component. Create a file with
“.module.css”‘ extension,
styles.module.css:
.paragraph{
color:"red";
border:1px solid black;
}
We can import this file inside the component and use it:
import styles from './styles.module.css';
Using useMemo( ) -
It is a React hook that is used for caching CPU-Expensive functions.
Sometimes in a React app, a CPU-Expensive function gets called repeatedly due to re-renders of a component, which can lead to slow rendering.
useMemo( ) hook can be used to cache such functions. By using useMemo( ), the CPU-Expensive function gets called only when it is needed.
Using React.PureComponent -
It is a base component class that checks state and props of a component to know whether the component should be updated.
Instead of using the simple React.Component, we can use React.PureComponent to reduce the re-renders of a component unnecessarily.
Lazy Loading -
It is a technique used to reduce the load time of a React app. Lazy loading helps reduce the risk of web app performances to minimal.
A key is a special string attribute that needs to be included when using lists of elements.
Example of a list using key:
const ids = [1,2,3,4,5];
const listElements = ids.map((id)=>{
return(
<li key={id.toString()}>
{id}
</li>
)
})
Importance of keys
Keys help react identify which elements were added, changed or removed.
Keys should be given to array elements for providing a unique identity for each element.
Without keys, React does not understand the order or uniqueness of each element.
With keys, React has an idea of which particular element was deleted,edited, and added.
Keys are generally used for displaying a list of data coming from an API.
***Note- Keys used within arrays should be unique among siblings. They need not be globally unique.
function ParentComponent(props) {
let [counter, setCounter] = useState(0);
As one can see in the code above, we are rendering the child component inside the parent component, by providing a prop called counterValue. Value
of the counter is being passed from the parent to the child component.
We can use the data passed by the parent component in the following way:
function ChildComponent(props) {
return (
<div>
<p>Value of counter: {props.counterValue}</p>
</div>
);
}
We use the props.counterValue to display the data passed on by the parent component.
Child Component to Parent Component (using callbacks)
This one is a bit tricky. We follow the steps below:
Create a callback in the parent component which takes in the data needed as a parameter.
Pass this callback as a prop to the child component.
Send data from the child component using the callback.
We are considering the same example above but in this case, we are going to pass the updated counterValue from child to parent.
Step1 and Step2: Create a callback in the parent component, pass this callback as a prop.
function ParentComponent(props) {
let [counter, setCounter] = useState(0);
return (
<div>
<p>Value of counter: {counter}</p>
<ChildComponent callbackFunc={callback} counterValue={counter} />
</div>
);
}
As one can see in the code above, we created a function called callback which takes in the data received from the child component as a parameter.
Next, we passed the function callback as a prop to the child component.
Step3: Pass data from child to the parent component.
function ChildComponent(props) {
let childCounterValue = props.counterValue;
return (
<div>
<button onClick={() => props.callbackFunc(++childCounterValue)}>
Increment Counter
</button>
</div>
);
}
In the code above, we have used the props.counterValue and set it to a variable called childCounterValue.
Next, on button click, we pass the incremented childCounterValue to the props.callbackFunc.
This way, we can pass data from the child to the parent component.
componentDidMount() {
// Listens to the changes added
GlobalDataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
// Listens to the changes removed
GlobalDataSource.removeChangeListener( this.handleChange);
}
handleChange() {
// States gets Update whenver data source changes
this.setState({
articles: GlobalDataSource.getArticles(),
});
}
render() {
return (
<div>
{this.state.articles.map((article) => (
<ArticleData article={article} key={article.id} />
))}
</div>
);
}
}
componentDidMount() {
// Listens to the changes added
GlobalDataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
// Listens to the changes removed
GlobalDataSource.removeChangeListener(this.handleChange);
}
handleChange() {
// States gets Update whenver data source changes
this.setState({
users: GlobalDataSource.getUsers(),
});
}
render() {
return (
<div>
{this.state.users.map((user) => (
<UserData user={user} key={user.id} />
))}
</div>
);
}
}
Notice the above components, both have similar functionality but, they are calling different methods to an API endpoint.
Let’s create a Higher Order Component to create an abstraction:
// Higher Order Component which takes a component
// as input and returns another component
// "GlobalDataSource" is some global data source
function HOC(WrappedComponent, selectData) {
return class extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
data: selectData(GlobalDataSource, props),
};
}
componentDidMount() {
// Listens to the changes added
GlobalDataSource.addChangeListener(this.handleChange);
}
componentWillUnmount() {
// Listens to the changes removed
GlobalDataSource.removeChangeListener( this.handleChange);
}
handleChange() {
this.setState({
data: selectData(GlobalDataSource, this.props),
});
}
render() {
// Rendering the wrapped component with the latest data data
return <WrappedComponent data={this.state.data} {...this.props} />;
}
};
}
Remember, we are not trying to change the functionality of each component, we are trying to share a single functionality across multiple components
using HOC.
Sometimes while developing React applications, there is a need to pass data from a component that is
higher in the hierarchy to a component that is deeply nested.
To pass data between such components, we pass props from a source component, and keep passing the
prop to the next component in the hierarchy till we reach the deeply nested component.
The disadvantage of using prop drilling is that the components that should otherwise be not aware of
the data have access to the data.
incrementCounter(){
this.setState(prevState => counterValue = prevState+1);
}
render(){
if(this.state.counter === 2){
throw new Error('Crashed');
}
return(
<div>
<button onClick={this.incrementCounter}>Increment Value</button>
<p>Value of counter: {this.state.counterValue}</p>
</div>
)
}
}
In the code above, when the counterValue equals to 2, we throw an error inside the render method.
When we are not using the error boundary, instead of seeing an error, we see a blank page.
Since any error inside the render method, leads to unmounting of the component.
To display an error that occurs inside the render method, we use error boundaries.
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h4>Something went wrong</h4>
}
return this.props.children;
}
}
In the code above, getDerivedStateFromError function renders the fallback UI interface when the render method has an error.
componentDidCatch logs the error information to an error tracking service.
Now with error boundary, we can render the CounterComponent in the following way:
<ErrorBoundary>
<CounterComponent/>
</ErrorBoundary>
1. Differentiate between Real DOM and Virtual DOM.
i. Events are named using camel case instead of just using the lowercase.
ii. Events are passed as functions instead of strings.
The event argument contains a set of properties, which are specific to an event. Each event type contains its own properties and behavior
which can be accessed via its event handler only.
Explain Flux.
Flux is an architectural pattern which enforces the uni-directional data flow. It controls derived data and enables communication between
multiple components using a central Store which has authority for all data. Any update in data throughout the application must occur here
only. Flux provides stability to the application and reduces run-time errors.
In case you are facing any challenges with these React interview questions, please comment on your problems in the section below.
It is used to provide an interface for websites and client applications to have access to data.
It can also be used to access data from the database and save data back to the database.
It supports different text formats such as XML, JSON, etc.
It is suitable or compatible with any type of browser and any type of device like mobile, desktop, web, etc.
It uses low bandwidth such as XML or JSON data, etc., and is therefore considered good for devices that have limited bandwidth such as
smartphones, etc.
From a business point of view, web API is more applicable for UI/UX, increases interest in the company’s product and services, increases
website traffic.
It contains additional layers that simply standardize communications and provide different options on how to format input and output.
It can be used with ASP.NET MVC and different types of web applications such as ASP.NET WebForms.
If one wants to create resource-oriented services, then Web API services are considered the best.
It also helps to develop REST-ful services and SOAP-based services.
Web API: It is an application programming interface for both web browsers and web servers. Browser API simply extends or increases the
functionality of web browsers whereas Server API simply extends or increases the functionality of web server.
It is good when one wants to expose an expensive It is good for creating services that uses
range of clients such as iPhones, browsers, mobile expedite transport channels such as TCP,
phones, tablets, etc. UDP, Named pipes, etc.
Web API uses all features of HTTP such as URIs, request/response headers, caching, versioning, various content formats, etc.
One does not have to define or explain any extra config setting for different devices in Web API.
Web API uses different text formats including XML because of which it is faster and more preferred for lightweight services.
Web API also supports MVC features whereas WCF does not support MVC features.
Web API provides more flexibility as compared to WCF.
Web API uses standard security like token authentication, basic authentication, etc., to provide secure service whereas WCF uses WS-I
standard to provide secure service.
The data format of REST is based on The data format of RESTful is based on JSON, HTTP, and
HTTP. Text.
{"city":"Mumbai","state":"Maharashtra"}
SOAP (Simple Object Access Protocol): It is a simple and lightweight protocol that is generally used for exchanging structured and typed
information on the Web. It works mostly with HTTP and RPC (Remote Procedure Call). This protocol is mainly used for B2B applications one
can define a data contract with it. SOAP messages are heavier in content and therefore use greater bandwidth.
For example:
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope" SOAP-ENV:
encodingStyle=" http://www.w3.org/2001/12/soap-encoding">
<soap:Body>
<Demo.guru99WebService xmlns="http://tempuri.org/"> <EmployeeID>int</EmployeeID>
</Demo.guru99WebService>
</soap:Body>
</SOAP-ENV:Envelope>
REST SOAP
Because of all the new features of Web API 2.0, it is considered an optimal choice and suitable development model that makes it easier to
develop RESTful services interfaces to different clients running on various platforms. It also supports configuring routes in the Web API
method or controller level.
12. Which of the following Open-source libraries is used by WEB API for
JSON serialization?
Json.NET library is generally used by Web API for JSON serialization.
Authentication Filter: It handles authentication and authenticates HTTP requests. It also helps to authenticate user detail. It checks the
identity of the user.
Authorization Filter: It handles authorization. It runs before controller action. This filter is used to check whether or not a user is
authenticated. If the user is not authenticated, then it returns an HTTP status code 401 without invoking the action.
AuthorizeAttribute is a built-in authorization filter provided by Web API.
Action Filter: It is attributing that one can apply to controller action or entire controller. It is used to add extra logic before or after controller
action executes. It is simply a way to add extra functionality to Web API services.
Exception Filter: It is used to handle exceptions that are unhandled in Web API. It is used whenever controller actions throw an unhandled
exception that is not HttpResponseException. It will implement an “IExceptionFilter” interface.
Override Filter: It is used to exclude specific action methods or controllers from the global filter or controller level filter. It is simply used to
modify the behavior of other filters for individual action methods.
18. What is MVC? Write difference between MVC and Web API?
MVC (Model, View, and Controller) is basically an application design model that comprises three interconnect parts I.e., model, view, and
controller. It allows coders to factor out different components of the application and update them more easily. It is mostly used for
developing model user interfaces. Its main purpose is to display patterns in structure for keeping display and data separate to enable both of
them to change without affecting others.
It can be used to build Web applications that reply as It is used to build HTTP services that reply
both data and views. only as data.
Desktop Applications
Mobile Applications
IOTs
Browsers
It provides the best platform for developing RESTful applications on .NET Framework.
It works the same way that HTTP works with help of HTTP verbs such as GET, POST, PUT, DELETE for all crud operations.
It provides enough flexibility in Web API creation.
It completely supports routing.
It also supports model binding, validation, Odata (Open Data Protocol) that allows creation and consumption of RESTful APIs.
It has the ability to develop custom help and test pages with help of ApiExplorer.
One can develop non-SOAP-based services such as plain XML, JSON strings, etc.
It also increases the TDD (Test Data-Driven) approach in the development of RESTful services.
21. What are new features used in ASP.NET Web API 2.0
ASP.NET Web API includes a number of new exciting features as given below:
Attribute Routing
CORS (Cross-Origin Resource Sharing)
OWIN (Open Web Interface for .NET) self-hosting
IHttpActionResult
Web API OData
// GetEmployee action
public HttpResponseMessage GetEmployee(int id)
{
Employee emp = EmployeeContext.Employees.Where(e => e.Id == id).FirstOrDefault()
;
if (emp != null)
{
return Request.CreateResponse<Employee>(HttpStatusCode.OK, emp);
} else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Employee
Not Found");
}
}
24. What do you mean by Caching and What are its types?
Caching is basically a technique or process of storing data somewhere or in the cache for future requests. The cache is a temporary storage
area. Caching keeps all frequently or recently accessed files or data in the cache memory and accesses them from the cache itself rather than
actual address of data or files. The cache interface simply improves the storage mechanism for request/response object pairs that are being
cached.
Advantages of Caching:
It is considered the best solution to ensure that data is served where it is needed to be served that too at a high level of efficiency which is
best for both client and server.
It delivers web objects faster to the end-user.
It reduces load time on the website server.
It leads to faster execution of any process.
It decreases network costs.
Types of Caching:
There are basically three types of caching as given below:
Page Caching
Data Caching
Fragment Caching
No, it's not true that ASP.NET Web API has replaced WCF. WCF was generally developed to develop SOAP-based services. ASP.NET Web API
is a new way to develop non-SOAP-based services such as XML, JSON, etc. WCF is still considered a better choice if one has their service
using HTTP as the transport and they want to move to some other transport like TCP, NetTCP, MSMQ, etc. WCF also allows one-way
communication or duplex communication.
26. What are the main return types supported in ASP. Net Web API?
It supports the following return types:
HttpResponseMessage
IHttpActionResult
Void
Other types such as string, int, etc.
Attribute-based routing: Web API 2 generally supports a new type of routing known as attribute routing. As the name suggests, it uses
attributes to define routes. It is the ability to add routes to the route table via attributes.
Authentication: It is a process that helps to identify and check users by their credentials such as password, username, etc. To have access to
the web API, firstly user credentials are needed to be passed in the request header. If user credentials are not passed into the request header,
then the server returns 401 status code (unauthorized). The best authentication to be used is OAuth 2.0.
Authorization: It is a process that helps to decide whether or not a user has access to perform an action. Authorization filters are used to
implement authorization.
HTTP GET: This method is used to get information or data from a respective server at a specified URL.
Example:
GET/RegisterStudent.asp?user=value1&pass=value2
HTTP POST: This method is used to send data or information to respective servers.
Example:
POST/RegisterStudent.asp HTTP/1.1
Host: www.guru99.com
user=value1&pass=value2
GET requests are less safe than POST. Post request is safer than GET.
Fiddler – Compose Tab -> Enter Request Headers -> Enter Request Body and then execute.
Conclusion
42. Conclusion
Web API is an extensible framework that serves us information from the server and is used for developing ASP.NET. It is totally based on Http
and is easy to define, expose and consume in a REST-ful way. It is considered an ideal platform for developing RESTful applications on .NET
framework. From the above Web API interview questions and answers, you can learn more about Web API, its importance, its benefits, etc.
1) What is Web API?
It's a not at all true that ASP.NET Web API has replaced WCF. In fact, it is another way of building non-SOAP based
services, i.e., plain XML or JSON string.
9) Web API uses which of the following open-source library for JSON serialization?
10) By default, Web API sends HTTP response with which of the following status code for all uncaught exception?
11) What is the biggest disadvantage of "Other Return Types" in Web API?
The biggest disadvantage of this approach is that you cannot directly return an error code like 404 error.
MaxAge = TimeSpan.FromMinutes(20)
};
return response;
For example:
Routes.MapHttpRoute(
Name: "ExampleWebAPIRoute",
routeTemplate: “api/{controller}/{id}
SOAP is an XML message format used in web service interactions. It allows to send messages over HTTP or JMS, but other
transport protocols can be used. It is also an XML-based messaging protocol for exchanging information among computers.
REST is used to make fewer data transfers between client and server which make it an ideal for using it in mobile apps.
Web API also supports HTTP protocol. Therefore, it reintroduces the traditional way of the HTTP verbs for communication.
16) How can we use Web API with ASP.NET Web Form?
17) How to you can limit Access to Web API to Specific HTTP Verb?
Attribute programming plays a important role. It is easy to restrict access to an ASP.NET Web API method to be called using
a particular HTTP method.
18) Can you use Web API with ASP.NET Web Form?
Yes, It is possible to use Web API with ASP.Net web form. As it is bundled with ASP.NET MVC framework. However, it can
be used with ASP.NET Web Form.
19) How Can assign alias name for ASP.NET Web API Action?
We can give alias name for Web API action same as in case of ASP.NET MVC by using "ActionName" attribute as follows:
[HttpPost]
[ActionName("SaveStudentInfo")]
TestApi is a utility library of APIs. Using this library tester developer can create testing tools and automated tests for a .NET
application using data-structure and algorithms.
It will be executed when exceptions are unhandled and thrown from a controller method. The reason for the exception can
be anything. Exception filters will implement "IExceptionFilter" interface.
[NotImplExceptionFilter]
23) How you can return View from ASP.NET Web API method?
No, we can't return a view from ASP.NET Web API Method. Web API creates HTTP services that render raw data. However,
it's also possible in ASP.NET MVC application.
GlobalConfiguration.Configuration.Filters.Add(new
MyTestCustomerStore.NotImplExceptionFilterAttribute());
REST represents REpresentational State Transfer; it is entirely a new aspect of writing a web app.
RESTFUL: It is term written by applying REST architectural concepts is called RESTful services. It focuses on system
resources and how the state of the resource should be transported over HTTP protocol.
Config.Routes.MapHttpRoute(
);
Several classes are available in Web API to handle errors. They are HttpError, Exception Filters, HttpResponseException,
and Registering Exception Filters.
28) What New Features comes with ASP.NET Web API 2.0?
The latest features of ASP.NET Web API framework v2.0 are as follows:
Attribute Routing
Cross-Origin Resource Sharing
External Authentication
Open Web Interface NET
HttpActionResult
Web API OData
29) How can you restrict access methods to specific HTTP verbs in Web API?
With the help of Attributes (like HTTP verbs), It is possible to implement access restrictions in Web API.
[HttpPost]
public void Method1(Class obj)
//logic
30) How can you pass multiple complex types in Web API?
paramList.Add(c);
paramList.Add(p);
32) Name the tools or API for developing or testing web api?
1. Jersey API
2. CFX
3. Axis
4. Restlet
REST is architectural style. It has defined guidelines for creating services which are scalable. REST used with HTTP
protocol using its verbs GET, PUT, POST and DELETE.
We can perform a Unit test using Web API tools like Fiddler.
Fiddler –Compose Tab -> Enter Request Headers -> Enter the Request Body and execute
35) How can we restrict access to methods with specific HTTP verbs in Web API?
Attribute programming is widely used for this functionality. Web API also allows restricting access of calling methods with the
help of specific HTTP verbs. It is also possible to define HTTP verbs as attribute over method.
[NotImplExceptionFilter]
38) Tell me the code snippet to show how we can return 404 errors from HttpError?
[NotImplExceptionFilter]
43) By default, Web API sends HTTP response with which of the following status code for all uncaught exception?
Several classes are available in Web API to handle errors. They are HttpError, HttpResponseException, Exception Filters,
Registering Exception Filters.
WCF services use the SOAP protocol while HTTP never use SOAP protocol. That’s why WebAPI services are lightweight
since SOAP is not used. It also reduces the data which is transferred to resume service. Moreover, it never needs too much
configuration. Therefore, the client can interact with the service by using the HTTP verbs.
MVC framework is used for developing applications which have User Interface. For that, views can be used for building a
user interface.
WebAPI is used for developing HTTP services. Other apps can also be called the WebAPI methods to fetch that data.
WebAPI can be consumed by any client which supports HTTP verbs such as GET, PUT, DELETE, POST. As WebAPI
services don’t need any configuration, they are very easy to consume by any client. Infract, even portable devices like
Mobile devices can easily consume WebAPI which is certainly the biggest advantages of this technology.
50) How can we make sure that Web API returns JSON data only?
To make Web API serialize the returning object to JSON format and returns JSON data only. For that you should add the
following code in WebApiConfig.cs class in any MVC Web API Project:
//JsonFormatter
//MediaTypeHeaderValue
Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("app
lication/json"));
//JsonFormatter
//MediaTypeHeaderValue
Config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("app
lication/json"))
JQuery
1. What is jQuery?
jQuery is a open source and most popular library for simiplifying interactions between DOM and
JavaScript.
jQuery is said to be a library of single JavaScript file which consists of DOM/CSS manipulations, event
effects or animations, AJAX functions and various commonly used plugins.
The css() method is used to change style property of the selected element.
User actions on a webpage are called events and handling responses to those is called event
handling. jQuery provides simple methods for attaching event handlers to selected elements.
When an event occurs, the provided function is executed.
jQuery.length property is used to count number of the elements of the jQuery object.
The each() method in jQuery allows us to loop through different datasets such as arrays or objects (even DOM objects).
It can be used to loop through a number of DOM objects from the same selectors.
For example, if you want to add a width=“600” to all the images in a page then we select all images and loop through each of them and
add width = "600" to each tag. We can write the code as below:
$("img").each(function(im){
$(this).attr("width","600")
});
$ is a jQuery object definer. In the above syntax, “this” is a DOM object and we can apply jQuery functions to only jQuery objects which is
why we convert the DOM object to jQuery object by wrapping it inside the $ definer.
We can also use each() to loop through the arrays of data and get the index and the value of the position of data inside the array.
For example,
var list = ["InterviewBit", "jQuery", "Questions"];
$.each(list, function(index, value){
console.log(index + " "+ value);
})
0 InterviewBit
1 jQuery
2 Questions
You can also use each() to loop through objects.
For example:
var obj = {"name":"InterviewBit","type": "jQuery"};
$.each(obj, function(key,value){
console.log(key + " - " + value);
})
name - InterviewBit
type - jQuery
11. What is the difference between javascript and jquery?
JavaScript is an interpreted language written in C and is combination of ECMAScript and DOM where jQuery is a JavaScript library
developed to run things faster and make things simplified for JavaScript. jQuery doesnt have the ECMAScript.
JavaScript requires long lines of code to code a functionality where in case of jQuery, just import the library and call the functions which
would reduce the programmer’s effort of coding.
JavaScript doesnt have the cross browser compatible functionality which is why a developer has to write code manually to implement the
functionality. Whereas the cross browser code compatibility is inbuilt in jQuery.
12. What are the selectors in jQuery? How many types of selectors in jQuery?
In order to work with any element on the web page, we would first need to find it. Selectors find the HTML elements in jQuery. Some of the most
commonly used and basic selectors are:
Name: Used to select all elements which matches the given element Name.
#ID: Used to select a single element which matches with the given ID
.Class: Used to select all elements which match with the given Class.
Universal (*): Used to select all elements available in a DOM.
Multiple Elements E, F, G: Used to selects the combined results of all the specified selectors E, F or G.
Attribute Selector: Used to select elements based on its attribute value.
13. Explain how CSS classes can be manipulated in HTML using jQuery.
Query provides several methods to manipulate the CSS classes assigned to HTML elements. The most important methods are addClass(),
removeClass() and toggleClass().
addClass(): This method adds one or more classes to the selected elements.
o Syntax: $(selector).addClass(className);
o You can also add multiple classes to the selector. Syntax:$(selector).addClass(class1, class2);
removeClass(): Similar to adding class, you can also remove the classes from the elements by using this method.
o The removeClass() method can remove a single class, multiple classes, or all classes at once from the selected elements.
o Syntax:
For removing one class: $(selector).removeClass(class1);
For removing multiple class: $(selector).removeClass(class1, class2, class 3);
For removing all classes at once: $(selector).removeClass()
toggleClass(): This method is used for adding or removing one or more classes from the selected elements in such a way that if the
selected element already has the class, then it is removed. Else if an element does not have the specified class, then it is added i.e.
it toggles the application of classes.
o Syntax: $(selector).toggleClass(className);
14. How to perform jQuery AJAX requests?
jQuery provides the ajax() method to perform an AJAX (asynchronous HTTP) request.
Syntax: $.ajax({name:value, name:value, ... }). The parameters specify one or more value of name-value pairs.
o url : this name specifies the URL to send the request to. Default is the current page.
o success(result,status,xhr) : success callback function which runs when the request succeeds
o error(xhr,status,error) : A function to run if the request fails.
o async : Boolean value that indicates whether the request should be handled asynchronous or not. Default value is true.
o complete(xhr,status) : A function to run when the request is completed (after success and error functions are handled)
o xhr : A function used for creating the XMLHttpRequest object
Example:
$.ajax({
url: "resourceURL",
async: false,
success: function(result){
$("div").html(result);
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}
});
The given code is an example of getting elements that satisfy multiple selectors at once. The function returns a jQuery object having the
results of the query.
The given code does a query to retrieve those <div> element with the id value firstDiv along with all <div> elements that has the class
value firstDiv and all elements that are children of the <ol id="items"> element and whose name attribute ends with the string firstDiv.
16. Consider the following code that exists in following HTML with the CSS:
<div id="expand"></div>
<style>
div#expand{
width: 50px;
height: 50px;
background-color: gray;
}
</style>
Write jQuery code to animate the #expand div, expanding it from 50 * 50 pixels to 300 * 300 pixels within five seconds.
We can do this by using the animate() function. We first need to have access to the div element which has id value of expand and then
apply animate function on the element as follows:
$("#expand").animate(
{
width: "300px",
height: "300px",
},
5000
);
The given code first selects all the <div> elements and applies width of 500px to them and adds all the <p> elements to the elements
selection after which the code can finally change the background color to yellow for all the <div> and <p> elements
The given code is an example of method chaining in jQuery which is used to accomplish a couple of things in one single instruction.
18. Can you explain the difference between jQuery.get() and jQuery.ajax()?
jQuery.ajax() allows the creation of highly-customized AJAX requests, with options for how long to wait for a response, what to do once the
request is successful, how to handle a failure scenarios, whether the request to be sent is blocking (synchronous) or non-blocking
(asynchronous), what format to expect as the response, and many more customizable options.
jQuery.get() is uses jQuery.ajax() underneath to create an AJAX request typically meant for simple retrieval of information.
o There are various other pre-built AJAX requests given by jQuery such as:
jQuery.post() for performing post requests
jQuery.getScript() meant for loading and then executing a JavaScript file from the server using GET request.
jQuery.getJSON() for loading JSON-encoded data from the server using a GET HTTP request.
19. Which of the two lines of code below is more efficient and
why? document.getElementById("interviewBit"); OR $("#interviewBit");
The code document.getElementById( "interviewBit" ); is more efficient because its the pure JavaScript version.
The reason being jQuery is built on top of JavaScript and internally uses its methods to make DOM manipulation easier. This introduces
some performance overhead. We need to remember that jQuery is not always better than pure JavaScript and we need to use it only if it
adds advantage to our project.
20. Can you write a jQuery code selector that needs to be used for querying all elements whose ID ends
with string “IB”?
The .promise() method returns a dynamically generated promise that is resolved when all actions of a certain type bound to the collection,
queued or not, have ended.
The method takes two optional arguments:
o type - The default type is “fx” which indicates that the returned promise is resolved only when all animations of the selected
elements have been completed.
o target - If a target object is specified, .promise() will attach to promise to that specified object and then return it rather than
creating a new one.
22. Consider the below code snippet and assume that there are 5 <div> elements on the page. What is
the difference between the start and end times displayed?
function getMinsSeconds() {
var dt = new Date();
return dt.getMinutes()+":"+dt.getSeconds();
}
For the above code, the difference between the start and end times will be 10 seconds.
This is because .promise() will wait for all <div> animations (here, all fadeOut() calls) to complete, the last one will complete 10 seconds
(i.e. 5 * 2 = 10 seconds) after the fadeOut() starts.
23. Can you tell the difference between prop() and attr()s?
Both prop() and attr() can be used to get or set the value of the specified property of an element attribute.
The attr() gives the default value of a property whereas prop() returns its current value.
MicroService
Download PDF
Microservice Architecture is an architectural development style which builds an application as a collection of small
autonomous services developed for a business domain.
Wiremock, 2.) Docker and 3.) Hysrix are important Microservices tool.
3) What is Monolithic Architecture? Monolithic architecture is like a big container in which all the software components of
an application are clubbed inside a single package.
Technology diversity, e., Microservices can mix easily with other frameworks, libraries, and databases
Fault isolation, e., a process failure should not bring the whole system down.
Greater support for smaller and parallel team
Independent deployment
Deployment time reduce
Spring cloud is an Integration software that integrates with external systems. It allows microservices framework to build
applications which perform restricted amounts of data processing.
6) Discuss uses of reports and dashboards in the environment of Microservices
Reports and dashboards help in monitoring and upkeep of Microservices. Tons of Application Monitoring Tools assist in this.
Changes done in a single data model does not affect Any changes in the data model affect the
other Microservices. entire database
Microservices focuses on products, not projects Monolithic put emphasize over the whole
project
Microservices always rely on each other. Therefore, they need to communicate with each other.
As it is distributed system, it is a heavily involved model.
If you are using Microservice architecture, you need to ready for operations overhead.
You need skilled professionals to support heterogeneously distributed microservices.
Microservice architecture is best suited for desktop, web, mobile devices, Smart TVs, Wearable, etc.
10) Tell me the name of some famous companies which are using Microservice architecture
Most large-scale websites like Twitter, Netflix, Amazon, have advanced from a monolithic architecture to a microservices
architecture.
11) What are the characteristics of Microservices?
Representational State Transfer (REST)/RESTful web services is an architectural style that helps computer systems to
communicate over the internet. These web services make microservices easier to understand and implement.
13) Explain three types of Tests for Microservices? In Microservice architecture tests are divided into three broad
categories:
At the bottom level test, we can perform a general test like performance and unit tests. These kinds of tests are
entirely automated.
At the middle level, we can perform exploratory tests like the stress tests and usability tests.
At the top level, we can conduct acceptance tests which are mostly fewer in numbers. It also helps stakeholders to
know about different software features.
Client certificates is a digital certificate used to make authenticated requests to a remote server. It is termed as a client
certificate.
It is an open source tool which allows testing interactions between service providers and consumers. However, it is
separated from the contract made. This increases the reliability of the Microservices applications.
OAuth means open authorization protocol. This protocol allows you to access the client applications on HTTP for third-party
providers GitHub, Facebook, etc. It helps you to share resources stored on one site with another site without the need for
their credentials.
End-to-end testing validates every process in the workflow is functioning correctly. It also ensures that the system works
together as a whole and satisfies all requirements.
Containers are easiest and effective method to manage the microservice based application. It also helps you to develop and
deploy individually. Docker also allows you to encapsulate your microservice in a container image along with its
dependencies. Microservice can use these elements without additional efforts.
Semantic monitoring combines automated tests with monitoring of the application. It allows you to find out reasons why your
business is not getting more profits.
Docker offers a container environment which can be used to host any application. This software application and the
dependencies that support it which are tightly-packaged together.
Reactive Extensions is also called Rx. It is a design pattern which allows collecting results by calling multiple services and
then compile a combined response. Rx is a popular tool in distributed systems which works exactly opposite to legacy flows.
Continuous monitoring is a method which is used for searching compliance and risk issues associated with a company’s
operational and financial environment. It contains human, processes, and working systems which support efficient and
actual operations.
It depends upon your project needs. However, in most cases, developers use HTTP/REST with JSON or Binary protocol.
However, they can use any communication protocol.