Quantcast
Channel: Interview Questions – Web Development Tutorial
Viewing all 26 articles
Browse latest View live

Top 10 ASP.NET MVC Interview Questions

0
0

A must have list of ASP.NET MVC Interview Questions and Answers with concepts and necessary code examples. If you understand following key concepts, you will definitely feel more comfortable during an interview. But along with that you need to prepare your practical skills on ASP.NET MVC technology.You can also find more related implementation details here:

UPDATE: Although this tutorial targets top 10 most important and frequently asked interview questions but I have added few more questions at the end for readers to help them well prepare for ASP.NET MVC5 interview.

Also, I have added Recent ASP.NET MVC Jobs at the end of this article that will definitely help you finding your dream job in Dubai, UAE.

ASP.NET MVC Interview Questions List

  1. Explain MVC (Model-View-Controller) in general?
  2. What is ASP.NET MVC?
  3. Difference between ASP.NET MVC and ASP.NET WebForms?
  4. What are the Core features of ASP.NET MVC?
  5. Can you please explain the request flow in ASP.NET MVC framework?
  6. What is Routing in ASP.NET MVC?
  7. What is the difference between ViewData, ViewBag and TempData?
  8. What are Action Methods in ASP.NET MVC?
  9. Explain the role of Model in ASP.NET MVC?
  10. What are Action Filters in ASP.NET MVC?

More Interview Questions….

1. Explain MVC (Model-View-Controller) in general?

MVC (Model-View-Controller) is an architectural software pattern that basically decouples various components of a web application. By using MVC pattern, we can develop applications that are more flexible to changes without affecting the other components of our application.

  •  “Model”, is basically domain data.
  •  “View”, is user interface to render domain data.
  •  “Controller”, translates user actions into appropriate operations performed on model.

MVC Architecture
Back to top

2. What is ASP.NET MVC?

ASP.NET MVC is a web development framework from Microsoft that is based on MVC (Model-View-Controller) architectural design pattern. Microsoft has streamlined the development of MVC based applications using ASP.NET MVC framework.Understanding ASP.NET MVC
Back to top

3. Difference between ASP.NET MVC and ASP.NET WebForms?

ASP.NET Web Forms uses Page controller pattern approach for rendering layout, whereas ASP.NET MVC uses Front controller approach. In case of Page controller approach, every page has its own controller i.e. code-behind file that processes the request. On the other hand, in ASP.NET MVC, a common controller for all pages processes the requests.
Follow the link for the difference between the ASP.NET MVC and ASP.NET WebForms.
Back to top

4. What are the Core features of ASP.NET MVC?

Core features of ASP.NET MVC framework are:

  • Clear separation of application concerns (Presentation and Business Logic). It reduces complexity that makes it ideal for large scale applications where multiple teams are working.
  • It’s an extensible as well as pluggable framework. We can plug components and further customize them easily.
  • It provides extensive support for URL Routing that helps to make friendly URLs (means friendly for human as well as Search Engines).
  • It supports for Test Driven Development (TDD) approach. In ASP.NET WebForms, testing support is dependent on Web Server but ASP.NET MVC makes it independent of Web Server, database or any other classes.
  • Support for existing ASP.NET features like membership and roles, authentication and authorization, provider model and caching etc.

Follow for detailed understanding of above mentioned core features.

Back to top

5. Can you please explain the request flow in ASP.NET MVC framework?

Request flow for ASP.NET MVC framework is as follows:
Request hits the controller coming from client. Controller plays its role and decides which model to use in order to serve the request. Further passing that model to view which then transforms the model and generate an appropriate response that is rendered to client.

ASP.NET MVC Request FlowYou can follow the link, in order to understand the Complete Application Life Cycle in ASP.NET MVC.
Back to top

6. What is Routing in ASP.NET MVC?

In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx file. On the other hand, ASP.NET MVC framework uses friendly URLs that more easily describe user’s action but not mapped to physical files. Let’s see below URLs for both ASP.NET and ASP.NET MVC.

//ASP.NET  approach – Pointing to physical files (Student.aspx)
//Displaying all students
http://locahost:XXXX/Student.aspx

//Displaying a student by Id = 5

http://locahost:XXXX/Student.aspx?Id=5

 

//ASP.NET MVC approach – Pointing to Controller i.e. Student
//Displaying all students
http://locahost:XXXX/Student

//Displaying student by Id = 5

http://locahost:XXXX/Student/5/

ASP.NET MVC framework uses a routing engine, that maps URLs to controller classes. We can define routing rules for the engine, so that it can map incoming request URLs to appropriate controller. Practically, when a user types a URL in a browser window for an ASP.NET MVC application and presses “go” button, routing engine uses routing rules that are defined in Global.asax file in order to parse the URL and find out the path of corresponding controller. You can find complete details of ASP.NET MVC Routing here.
Back to top

7. What is the difference between ViewData, ViewBag and TempData?

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options i.e. ViewData, ViewBag and TempData.

Both ViewBag and ViewData are used to to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs. So, in short, its a mechanism to maintain state between controller and corresponding view. ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn’t have typecasting and null checks.

TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects i.e from one controller to the other controller.ViewData Vs ViewBag Vs TempData

You can easily find detailed examples for implementation of ViewBag, ViewData and TempData here.
Back to top

8. What are Action Methods in ASP.NET MVC?

As I already explained about request flow in ASP.NET MVC framework that request coming from client hits controller first. Actually MVC application determines the corresponding controller by using routing rules defined in Global.asax. And controllers have specific methods for each user actions. Each request coming to controller is for a specific Action Method. The following code sample, “ShowBook” is an example of an Action Method.

  public ViewResult ShowBook(int id)
  {
           var computerBook = db.Books.Where(p => P.BookID == id).First();
           return View(computerBook);
  }

Action methods perform certain operation using Model and return result back to View. As in above example, ShowBook is an action method that takes an Id as input, fetch specific book data and returns back to View as ViewResult. In ASP.NET MVC, we have many built-in ActionResults type:

  • ViewResult
  • PartialViewResult
  • RedirectResult
  • RedirectToRouteResult
  • ContentResult
  • JsonResult
  • EmptyResult
  • and many more….

For a complete list of available ActionResults types with Helper methods, please click here.

Important Note: All public methods of a Controller in ASP.NET MVC framework are considered to be Action Methods by default. If we want our controller to have a Non Action Method, we need to explicitly mark it with NonAction attribute as follows:

[NonAction]
public void MyNonActionMethod() { ….. }

Back to top

9.Explain the role of Model in ASP.NET MVC?

One of the core feature of ASP.NET MVC is that it separates the input and UI logic from business logic. Role of Model in ASP.NET MVC is to contain all application logic including validation, business and data access logic except view i.e. input and controller i.e UI logic.
Model is normally responsible for accessing data from some persistent medium like database and manipulate it, so you can expect that interviewer can ask questions on database access topics here along with ASP.NET MVC Interview Questions.
Back to top

10.What are Action Filters in ASP.NET MVC?

If we need to apply some specific logic before or after action methods, we use action filters. We can apply these action filters to a controller or a specific controller action. Action filters are basically custom classes that provide a mean for adding pre-action or post-action behavior to controller actions.Action Filters in ASP.NET MVCFor example,

  • Authorize filter can be used to restrict access to a specific user or a role.
  • OutputCache filter can cache the output of a controller action for a specific duration.
  • and more…

Back to top

More Interview Questions on ASP.NET MVC

What are the new features introduced in ASP.NET MVC5?

ASP.NET MVC5 was introduced with following exciting features:

  • ASP.NET Identity
  • Authentication Filters
  • Filter Overrides
  • Scaffolding
  • Bootstrap
  • Attribute Routing
For details on above ASP.NET MVC5 new features, kindly follow here.
Back to top

What is a ViewEngine in ASP.NET MVC?

“View Engine in ASP.NET MVC is used to translate our views to HTML and then render to browser.”
There are few View Engines available for ASP.NET MVC but commonly used View Engines are Razor, Web Forms/ASPX, NHaml and Spark etc. Most of the developers are familiar with Web Forms View Engine (ASPX) and Razor View Engine.

  • Web Form View Engine was with ASP.NET MVC since beginning.
  • Razor View Engine was introduced later in MVC3.
  • NHaml is an open source view engine since 2007.
  • Spark is also an open source since 2008.

ASP.NET MVC View EngineBack to top

What is the difference between Razor View Engine and ASPX View Engine?

I have written a separate detailed blog post to understand the  Difference between ASPX View Engine and Razor View Engine. You can follow the link to get detailed step by step description  here. Most important differences are listed below:

ASPX View Engine

Razor View Engine

WebForms View Engine uses namespace “System.Web.Mvc.WebFormViewEngine”. “System.Web.Razor” is the namespace for Razor View Engine.
Comparatively fast. A little bit slower than ASPX View Engine.
Nothing like Test Driven Development Good support for Test Driven Development.
Syntax for ASPX View Engine is inherited from Web Forms pages as:
<%= employee.FullName %>
Syntax for Razor View Engine is
comparatively less and clean.
@employee.FullName

Back to top

What is a ViewModel in ASP.NET MVC?

A ViewModel basically acts as a single model object for multiple domain models, facilitating to have only one optimized object for View to render. Below diagram clearly express the idea of ViewModel in ASP.NET MVC:ViewModel in ASP.NET MVC

There are multiple scenarios where using ViewModel becomes obvious choice. For example:

  • Parent-Child View Scenario
  • Reports where often aggregated data required
  • Model object having lookup data
  • Dashboards displaying data from multiple sources

Back to top

What are ASP.NET MVC HtmlHelpers?

ASP.NET MVC HtmlHelpers fulfills almost the same purpose as that of ASP.NET Web From Controls. For imlementation point of view, HtmlHelper basically is a method that returns a string ( i.e. an HTML string to render HTML tags). So, in ASP.NET MVC we have HtmlHelpers for links, Images and for Html form elements etc. as follows:

@Html.ActionLink(“WebDev Consulting Company Profile”, “CompanyInfo”) will render:
<a href=”/Site/CompanyInfo”>WebDev Consulting Company Profile</a>
and
@Html.TextBox(“strEmployeeName”) renders:
<input id=”strEmployeeName” name=”strEmployeeName” type=”text” value=”” />

For a complete reference to Standard ASP.NET MVC Html Helpers, Click Here.

Note: Html Helpers are comparatively lightweight because these don’t have ViewState and event model as for ASP.NET Web Form Controls.

We can also create our Custom Html Helpers to fulfill specific application requirements. There are 2 ways to create custom HtmlHelpers as follows:Custom Html Helpers
Back to top

What is Bootstrap in MVC5?

Bootstrap (a front-end framework) is an open source collection of tools that contains HTML and CSS-based design templates along with Javascript to create a responsive design for web applications. Bootstrap provides a base collection including layouts, base CSS, JavaScript widgets, customizable components and plugins.

Project Template in ASP.NET MVC5 is now using bootstrap that enhances look and feel with easy customization. Bootstrap version 3 is added to ASP.NET MVC5 template as shown below:Bootstrap Template in MVC5
Back to top

Kindly explain Attribute Routing in ASP.NET MVC5?

We already have discussed about Routing in Question#6 that in ASP.NET MVC, we use friendly URLs that are mapped to controller’s actions instead of physical files as in case of ASP.NET WebForms. Now in ASP.NET MVC5, we can use attributes to define routes giving better control over the URIs.

We can easily define routes with Controller’s action methods as follows:Attribute Routing in MVC5

Note: Remember that conventional routing approach is not discarded, it’s still there and fully functional. Also, we can use both routing techniques in a same application. Click here for more details on Attribute Routing.

Back to top

What is Scaffolding in ASP.NET MVC? and what are the advantages of using it?

We (developers) spent most of our time writing code for CRUD operations that is connecting to a database and performing operations like Create, Retrieve, Update and Delete. Microsoft introduces a very powerful feature called Scaffolding that does the job of writing CRUD operations code for us.

Scaffolding is basically a Code Generation framework. Scaffolding Engine generates basic controllers as well as views for the models using Micrsoft’s T4 template. Scaffolding blends with Entity Framework and creates the instance for the mapped entity model and generates code of all CRUD Operations. As a result we get the basic structure for a tedious and repeatative task.

You can find a detailed Web Development Tutorial with implementation on ASP.NET MVC Scaffolding here.

ASP.NET MVC Scaffolding
Following are the few advantages of Scaffolding:
  • RAD approach for data-driven web applications.
  • Minimal effort to improve the Views.
  • Data Validation based on database schema.
  • Easily created filters for foreign key or boolean fields.

Back to top

Briefly explain ASP.NET Identity?

Microsoft introduces ASP.NET Identity as a system to manage access in ASP.NET application on premises and also in the cloud. There were issues with Membership Provider Model especially when we want to implement more advanced security features in our applications, so ASP.NET Identity gets away from the membership provider model.

If we look into the history of membership, its like follows:

  • ASP.NET 2.0 Membership (VS 2005)
    • Forms Authentication
    • Sql Server Based Membership
  • ASP.NET Simple Membership (VS 2010)
    • Easy to customize profile
    • ASP.NET Web Pages
  • ASP.NET Universal Providers (VS2012)
    • Support Sql Azure

ASP.NET Identity is much improved system to manage access to our application and services.ASP.NET Identity

For more information on ASP.NET Identity, please follow here.
Back to top

ASP.NET MVC is an amazing framework for developing applications. Above mentioned  ASP.NET MVC interview questions must be prepared before appearing for a MVC interview.


ASP.NET MVC Jobs in Dubai, United Arab Emirates [Updated Daily]

Top ASP.NET MVC Jobs

.Net developer
Source: Shine.com
Details: ASP.NET, MVC, WCF, SQL SERVER / ORACLE Database, C#.NET 1. Strong in OOPS concepts 2....  More
20 days ago

UAE 23-June-2015

Middle East Opportunity for IT Web Developer
Source: monstergulf
Details: Server-side development using .NET Framework 4.5, C# and ASP.NET MVC. Experience on SQL Server & database management system....  More
3 days ago

Dubai 09-July-2015

C# ASP.NET (MVC) Developer
Source: Akhtaboot
Details: We are looking for C# .Net Developer with MVC expertise. Well verse with web architecture and model view MVC, MVVM etc. Desired Skills and Expertise....  More
26 days ago

Dubai 16-June-2015

Computer Programmers
Source: Way to Gulf
Details: Application development, using C#, .Net, ASP.Net, ASP.Net MVC, MS SQL. Candidate having development experience using PowerBuilder and web....  More
9 days ago

Dubai 03-July-2015

Mobile Application Developer
Source: Michael Page AE
Details: ASP.NET, MVC, Episerver. The Mobile Application Developer will be responsible for creating and maintaining storage and coded solutions as well as improving...  More
6 days ago

Dubai 06-July-2015

Required Software Developer
Source: Gulfvisit
Details: Required Software Developer, with experience in ASP.net, ASP.net MVC, JQuery, Angular JS, Oracle, MS SQL, Android....  More
12 days ago

Dubai 30-June-2015

.NET MVC DEVELOPER, Dubai, Immediate Availability
Source: dubizzle.com
Details: C#/VB/ASP.net, MVC, Web services. Candidate should have strong academic background in the area of Computer Sciences/Engineering or equivalent studies, 2+ years...  More
19 days ago

Dubai 23-June-2015

Computer Programmers
Source: Gulfvisit
Details: Computer Programmers, having development experience using PowerBuilder and web application development, using C#, .Net, ASP.Net, ASP.Net MVC, MS SQL, excellent...  More
17 days ago

Dubai 25-June-2015

ASP.NET MVC Developer
Source: dubizzle.com
Details: Design pattern knowledge (MVVM, MVC, etc.). We are seeking a strong ASP.NET MVC / C# / SQL Developer for custom web applications....  More
28 days ago

Sharjah 14-June-2015

Software Developer - UAE
Source: Oilandgasjobsearch.com
Details: 4+ years experience- Knowledge in C#, Asp.Net MVC 4 or later, SQL Server (Should have done at least one project using Asp.Net MVC) - Project Duration:....  More
4 days ago

UAE 08-July-2015

Computer Programmers
Source: Gulf News GNAds4u
Details: Computer Programmers, having development experience using PowerBuilder and web application development, using C#, .Net, ASP.Net, ASP.Net MVC, MS SQL, excellent...  More
17 days ago

Dubai 25-June-2015

SENIOR WEB DEVELOPER
Source: dubizzle.com
Details: C#, ASP.NET MVC. A well reputed GPS tracking solutions are looking for a Sr....  More
25 days ago

Dubai 17-June-2015

C# ASP.NET (MVC) Developer (6 months Contract)
Source: Indeed
Details: We are looking for C# .Net Developer with MVC expertise. Well verse with web architecture and model view MVC, MVVM etc. Job Description and Requirements....  More
20 hours ago

Dubai 12-July-2015

Software Developer
Source: Indeed
Details: ASP .NET MVC, C#, WCF, Web API. A respective company in Dubai is currently looking for a Software Developer who has the following skills below:....  More
30+ days ago

Dubai 01-June-2015

MCSD - Web Applications

Top 10 Interview Questions and Answers Series:

The post Top 10 ASP.NET MVC Interview Questions appeared first on Web Development Tutorial.


Top 10 ASP.NET Interview Questions and Answers

0
0

“ASP.NET is a web application development framework for building web sites and web applications that follows object oriented programming approach”

Following are the top 10 commonly asked Interview Questions with detailed answers on ASP.NET technology. I have also prepared a comprehensive Tutorial Series of ASP.NET Interview Questions that you can further read through to better prepare for your ASP.NET interview.

ASP.NET Interview Questions List

1. What is the concept of Postback in ASP.NET?

A postback is a request sent from a client to server from the same page user is already working with.
ASP.NET was introduced with a mechanism to post an HTTP POST request back to the same page. It’s basically posting a complete page back to server (i.e. sending all of its data) on same page. So, the whole page is refreshed.

In below diagram, when first request is made from client to server for a web page (say a simple registration form), IsPostback property value will be false. It will be a GET request that may be initiated by:

  • typing a web page URL in a browser window or
  • using JavaScript window.open method
  • or, clicking a hyperlink on a webpage page.

After user filled the returned form and presses a button (say submit button, or use JavaScript to submit form), an HTTP Post request is made to server on same page with data as shown in point 3. This time  IsPostback property value will be true. Server processes the request and returns a response back to client.

Understanding Postback in ASP.NET
Another concept related to this approach is “Callback” that is also asked sometimes during a technical interview question. Click here to understand Postback Vs Callback in ASP.NET.

Back to top

2. Difference between ASP.NET WebForms and ASP.NET MVC?

ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In this approach, every page has it’s own controller i.e. code-behind file that processes the request. On the other hand, ASP.NET MVC uses Front Controller approach. In this approach a common controller for all pages, processes the requests.ASP.NET MVC Vs ASP.NET WebForms
Please follow for detailed information on WebForms Vs MVC.

Back to top

3. Please briefly explain ASP.NET Page life Cycle?

ASP.NET page passes through a series of steps during its life cycle. Following is the high-level explanation of life cycle stages/steps.

Initialization: Controls raise their Init event in this stage.Objects and variables are initializes for complete lifecycle of request.
LoadViewState: is a post back stage and loads the view state for the controls that enabled its view state property.
ASP.NET Page Life Cycle

LoadPostBackData: is also a post back stage and loads the data posted for the controls and update them. 
Load: In this stage page as well as all the controls raise their Load event. Till this stage all the controls are initialized and loaded. In most of the cases, we are coding this event handler.
RaisePostBackEvent: is again a postback stage. For example, it’s raise against a button click event. We can easily put our code here to perform certain actions.
SaveViewState: Finally, controls state is saved in this stage before Rendering HTML.
Render: This is the stage where HTML is generated for the page.
Dispose: Lastly, all objects associated with the request are cleaned up.

For very detailed explanation of Page Life Cycle is explained here.
Back to top

4. What is the difference between custom controls and user controls?

Custom controls are basically compiled code i.e. DLLs. These can be easily added to toolbox, so it can be easily used across multiple projects using drag and drop approach. These controls are comparatively hard to create.
But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy to create but tightly couple with respect to User Interface and code. In order to use across multiple projects, we need to copy and paste to the other project as well.
Back to top

5. What is the concept of view state in ASP.NET?

As in earlier question, we understood the concept of postback. So, in order to maintain the state between postbacks, ASP.NET provides a mechanism called view state. Hidden form fields are used to store the state of objects on client side and returned back to server in subsequent request (as postback occurs).

If we see the view source for an ASP.NET web page, we will find that hidden form field with Id = “__VIEWSTATE” something like the following:View State in ASP.NET
Back to top

6. Difference between Response.Redirect and Server.Transfer?

In case of Response.Redirect, a new request is generated from client-side for redirected page. It’s a kind of additional round trip. As new request is generated from client, so the new URL is visible to user in browser after redirection.
While in case of Server.Transfer, a request is transferred from one page to another without making a round trip from client. For the end user, URL remains the same in browser even after transferring to another page.Response.Redirect Vs Server.Transfer
Back to top

7. Please briefly explain the usage of Global.asax?

Global.asax is basically ASP.NET Application file. It’s a place to write code for Application-level events such as Application start, Application end, Session start and end, Application error etc. raised by ASP.NET or by HTTP Modules.

There is a good list of events that are fired but following are few of the important events in Global.asax:

  • Application_Init occurs in case of application initialization for the very first time.
  • Application_Start fires on application start.
  • Session_Start fires when a new user session starts
  • Application_Error occurs in case of an unhandled exception generated from application.
  • Session_End fires when user session ends.
  • Application_End fires when application ends or time out.

ASP.NET Online Test
Back to top

8. What are the different types of Validation controls in ASP.NET?

In order to validate user input, ASP.NET provides validation server controls. All validation controls inherits from BaseValidator class which contains the common validation properties and methods like ControlToValidate, Enabled, IsValid, EnableClientScript, ValidationGroup,Validate() etc.

ASP.Net provides a range of validation controls:

  • RequiredFieldValidator validates compulsory/required input.
  • RangeValidator validates the range. Validates that input falls between the given range values.
  • CompareValidator validates or compares the input of a control with another control value or with a fixed value.
  • RegularExpressionValidator validates input value against a defined regular expression pattern.
  • CustomValidator allows to customize the validation logic with respect to our application logic.
  • ValidationSummary displays all errors on page collectively.

Back to top

9. What are the types of Authentication in ASP.NET?

There are three types of authentication available in ASP.NET:

  • Windows Authentication: This authentication method uses built-in windows security features to authenticate user.
  • Forms Authentication: authenticate against a customized list of users or users in a database.
  • Passport Authentication: validates against Microsoft Passport service which is basically a centralized authentication service.

Back to top

10. What are Session state modes in ASP.NET?

ASP.NET supports different session state storage options:

  • In-Process is the default approach. It stores session state locally on same web server memory where the application is running.
  • StateServer mode stores session state in a process other than the one where application is running. Naturally, it has added advantages that session state is accessible from multiple web servers in a Web Farm and also session state will remain preserved even web application is restarted.
  • SQLServer mode stores session state in SQL Server database. It has the same advantages as that of StateServer.
  • Custom modes allows to define our custom storage provider.
  • Off mode disables session storage.

SesionState Modes in ASP.NETBack to top

I strongly believe that every asp.net web developer should prepare and understand the above discussed interview questions. You can follow here for Comprehensive list of ASP.NET Interview Questions. 

Top 10 Interview Questions and Answers Series:

The post Top 10 ASP.NET Interview Questions and Answers appeared first on Web Development Tutorial.

ASP.NET Interview Questions for Beginners and Professionals – Part 1

0
0
This ASP.NET Tutorial is an extension to my previous tutorial “Top 10 ASP.NET Interview Questions and Answers“. In previous tutorial, focus was to present you with the most important and top ASP.NET Interview Questions that are normally asked during an ASP.NET developer Interview. Here in this article, I’ll try to further extend those important questions as well as add more important questions.

Basically, this is how an interviewer normally does? Interviewer asked a question about a technical concept at high level. If he gets a right answer, he further goes into details related to that particular concept and its implementation details.

For example, in previous article, we asked about the concept of View State in ASP.NET but in this tutorial, we will further explore the View State concept with more questions. But we will not repeat the questions already presented in previous post, so it’s highly recommended to go through that ASP.NET Interview Questions tutorial first.

You can follow other Parts of this ASP.NET Interview Questions Series as:

ASP.NET Interview Questions List – Part 1

What are HttpHandlers and HttpModules in ASP.NET?

In order to fully comprehend the concept of HttpHandlers and HttpModules, I have written a detailed ASP.NET Tutorial. Here I am defining both the concepts as follows:

HttpHandler: ASP.NET Engine uses HttpHandlers to handle specific requests on the basis of it’s extensions. ASP.NET Page Handler handles all requests coming for (.aspx) pages. We can define our own custom HttpHandler to handle a specific request with a specific extension, say .jpeg, .gif, or .ahmad. But there will always be only one handler for a specific request.

HttpModule: ASP.NET Engine uses HttpModules to inject some specific functionality along with ASP.NET default functionality for all incoming requests regardless of its extensions. There are a number of built-in modules already available in ASP.NET HTTP Pipeline. But we can write our own custom HTTP module to perform some additional functionality (for example, URL rewriting or implementing some security mechanism) for all incoming requests.

For more details about HttpHandlers and HttpModules in ASP.NET, you can follow MSDN link here.
Back to top

What is State Management?

HTTP is a stateless protocol by nature. So, we need some mechanism to preserve state (i.e. state of a webpage, a control or an object etc.) between subsequent requests to server from one or more clients. And this mechanism is referred as State Management.

Back to top

What are the State Management Techniques used in ASP.NET?

State Management techniques used in ASP.NET can be categorized in two types:

  1. Client-Side State Management
    • View State
    • Control State
    • Hidden Fields
    • Cookies
    • Query String
  2. Server-Side State Management
    • Application State
    • Session State
    • Profile Properties
    • Cache
ASP.NET State Management

Back to top

What is ViewState? or Explain ViewState as State Management Technique?

ViewState is one of the Client-Side State Management techniques that provides page-level state management, which means state is preserved between subsequent requests to same page. By using this technique, state of the page along with its controls is stored in a hidden form field  i.e. “__VIEWSTATE” and this field is again available on server when page is posted back with HTTP Request.
You can find this hidden field by looking into view source of an .ASPX page as:

<input type=”hidden” name=”__VIEWSTATE” value=”wEPDwUKMTM4OTIxNTEzNA9kFgJmD2QWAgIBD2QWAgIDDxYCHgVzdHlsZQV” />

ViewState data is encoded in Base64 String encoded format.
Back to top

Can we Enable/Disable ViewState?

Yes, ViewState can be enabled or disable at different levels:

  • Control Level
    ViewState for a specific control can be enabled or disabled by setting EnableViewState property as follows:
aControl.EnableViewState = false;
  • Page Level
    We can enable/disable ViewState for a complete page as follows:
    <%@ Page Language=”C#” EnableViewState=”false” %>
  • Application Level
    For whole application, we can enable/disable views in configuration file as follows:
    <pages enableViewState=”false”>
        ….
    </pages>

Back to top

What is the difference between Session.Clear() and Session.Abandon() in ASP.NET?

As we understand that Session is a Collection and it stores data as Key/Value pair. So,
Session.Clear() clears all the session values but doesn’t destroy the Session. however,
 Session.Abandon() destroys the session object.
In other words, Session.Clear() is like deleting all files inside a folder (say “Root”) but Session.Abandon() means deleting the “Root” folder.

Back to top

What is the difference between Application and Session State?

Application state is basically a common data repository for an application’s all users and their all sessions. On the other hand, Session state is specific to a single user session. Following diagram explains the difference between two state management techniques:Application Vs Session State Management
So, we can store data in application state object that is common for all users of a particular application as follows:

//Set Value
Application[“UsersCounter”] = Convert.ToInt32(Application[“UsersCounter”]) + 1;
//Retrieve Value
lblUsersCounter.Text = Application[“UsersCounter”].ToString();

It’s recommended to store smaller size values in application object.

Session object can store data for a specific session of user. Storage and retrieval is also simple just as for application object.

//Set Value
Session[“ProductsCount”] = Convert.ToInt32(Session[“ProductsCount”]) + 1;
//Retrieve Value
lblProductsCounter.Text = Session[“ProductsCount”].ToString();

Interview Questions about Session State Modes and Session_Start/Session_End events in Global.asax are already explained here.

Back to top

What is the difference between Label Control and Literal Control?

A Label control in ASP.NET renders text inside <span> tags while a Literal Control renders just the text without any tags.
With Label controls we can easily apply styles using it’s CssClass property, however, if we don’t want to apply style/formatting, it’s better to go for a Literal control.
Back to top

Hyperlink Vs LinkButton in ASP.NET?

A Hyperlink just redirects to a given URL identified by “NavigateURL” property. However a LinkButton which actually displays a Hyperlink style button causes a postback to the same page but it doesn’t redirect to a given URL.

Validation Controls related Interview Questions are already given in previous post here.
Back to top

Hopefully, this pool of ASP.NET Interview Questions and Answers along with previous list of Top 10 will be helpful for ASP.NET Developers.

Next to Part 2>>>ASP.NET Online Test

Top 10 Interview Questions and Answers Series:

The post ASP.NET Interview Questions for Beginners and Professionals – Part 1 appeared first on Web Development Tutorial.

Top 10 ASP.NET AJAX Interview Questions

0
0

Exploring key features/capabilities of ASP.NET and getting answers for ASP.NET Interview Questions in this Web Development Tutorial series, we have reached this Part-5 with a set of questions on ASP.NET and AJAX (Asynchronous JavaScript and XML).What we have covered so far can be summarized as follows:

So, let’s keep exploring further ASP.NET technology concepts through Interview Questions Series.

ASP.NET AJAX Interview Questions List

Define AJAX?

AJAX stands for “Asynchronous JavaScript and XML”. It’s basically a technique for creating Rich Internet Applications (RIA) that are faster as well as more interactive, using a combination of commonly used techniques as HTML/XHTML, CSS, Document Object Model (DOM), JavaScript, XML/XSLT and XMLHttpRequest object.
XMLHttpRequest object is the key basis of AJAX and makes it possible to communicate with the web server asynchronously and exchange data. As compared to a traditional request which returns a complete web page,  partial web page is returned as response to an AJAX request.
AJAX Request Processing

Back to top


::::: Free Practical Guide to ASP.NET MVC Web API (Web Edition | PDF Download) :::::


Please elaborate XMLHttpRequest Object further?

XMLHttpRequest is the core object in AJAX technology regardless of any implementation. XMLHttpRequest object is used to exchange data with a server seamlessly. Basically JavaScript uses this Object to exchange XML as well as text data between client and server. An AJAX implementation uses this object and communicate with server but it doesn’t require the complete page to be refreshed.

Back to top

How to send a request to server using XMLHttpRequest Object?

We can send a request to server using HTTP GET and POST methods as follows:
//Simple GET Request
var xmlHttp = new XMLHttpRequest();
xmlHttp.open(“GET”, “TestFile.txt”, true);
xmlHttp.send();
//Simple POST Request
var xmlHttp = new XMLHttpRequest();
xmlHttp.open(“POST”, “TestFile.txt”, true);
xmlHttp.send();

Back to top

What is ASP.NET AJAX?

Microsoft provided an implementation of AJAX functionality known as ASP.NET AJAX.
As we discussed in above interview question that AJAX is a combination of various techniques, so Microsoft simplified the usage of these techniques with its own implementation. ASP.NET AJAX is a set of extensions to ASP.NET and comes with reusable AJAX controls. Using ASP.NET AJAX, we can develop applications that can update partial page instead of a complete page refresh.

Back to top

Difference between Synchronous and Asynchronous Postback?

In Synchronous postback, complete web page is sent to server and in return rendering the output (i.e. complete page), whereas in case of Asynchronous postback, partial page goes to the server and renders only partial (required) part of the page.
Normally a method making Synchronous call always waits for response to do next task (i.e. might be another call). On the other hand, for Asynchronous, no waiting required as illustrated by below figure:Synchronous Vs Asynchronous

Back to top

What are the basic controls in ASP.NET AJAX?

Following controls can be considered as core AJAX controls in ASP.NET.

  • ScriptManager
  • ScriptManagerProxy
  • UpdatePanel
  • UpdateProgress
  • Timer

Later more controls are added to ASP.NET AJAX library e.g. Script Loader, Client Data Context, Client Data Access, jQuery Integration etc. For complete reference, look for AJAX Control Toolkit.

Back to top

What is a ScriptManager in ASP.NET AJAX?

In order to use AJAX functionality on a web page, we add a ScriptManager control to the page in most of the scenarios, because ScriptManager control register AJAX library scripts to that particular web page. We can have only one ScriptManager per page.

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”></asp:ScriptManager>

ScriptManager basically manages all ASP.NET AJAX resources of a web page, creates proxies for asynchronous web service call and also manages partial page updates… etc.

Back to top

ScriptManager Vs ScriptManagerProxy?

As we understand that we can have only one ScriptManager control on a page but we can have multiple ScriptManagerProxy controls.
Consider a scenario that we have ScriptManager in our MasterPage that is available for all content pages. Now, we wanted to register a web service in a particular page. So, we will not add another ScriptManager to that page instead we will add ScriptManagerProxy to it in order to avoid error.
Back to top

What is the role of UpdatePanel in ASP.NET AJAX?

UpdatePanel is the control that facilitate the partial page rendering functionality in an ASP.NET application. As discussed earlier that using ASP.NET AJAX, we can communicate with a web server asynchronously and update a part of a page without a complete page postback. In order to apply partial page update/rendering, we can add one or more UpdatePanel controls to our ASP.NET Page as follows:
   <asp:ScriptManager ID=”ScriptManager1″ runat=”server”></asp:ScriptManager>
<asp:UpdatePanel ID=”UpdatePanel1″ runat=”server”>
            <ContentTemplate>
                <asp:Label ID=”lblPanel” runat=”server” Text=”Update Panel Added.”></asp:Label><br />
                <asp:Button ID=”btnTestButton” 
                                   runat=”server” 
                                  OnClick=”btnTestButton_Click” 
                                  Text=”Test Button” />
      </ContentTemplate>
    </asp:UpdatePanel>

Back to top

What are the limitations of AJAX?

  • AJAX on an application will not work if JavaScript is disabled.
  • In some scenarios, it exposes vulnerability.
  • It will always be difficult to bookmark application state.
  • Application behavior may be slow in some scenarios, because of different loading time of controls on a single page.

Back to top

Hopefully, this ASP.NET Tutorial will clear more concepts about AJAX technology usage in ASP.NET.

Other Related Articles:

ASP.NET AJAX Online Test

Top 10 Interview Questions and Answers Series:

The post Top 10 ASP.NET AJAX Interview Questions appeared first on Web Development Tutorial.

Top 10 ASP.NET Web API Interview Questions

0
0

In this ASP.NET Interview Questions Series, so far we have covered questions related to the core of ASP.NET technology. In this part-6 of ASP.NET Tutorial series, we will cover top 10 interview questions related to ASP.NET Web API framework.What we have covered so far can be summarized as follows:

So, let’s dive deeper to understand ASP.NET Web API technology concepts through Interview Questions.

ASP.NET Interview Questions List – Part 1

What is ASP.NET Web API?

ASP.NET Web API is a framework that simplifies building HTTP services for broader range of clients (including browsers as well as mobile devices) on top of .NET Framework. Using ASP.NET Web API we can create non-SOAP based services like plain XML or JSON strings etc. with many other advantages including:

  • Create resource-oriented services using the full features of HTTP.
  • Exposing services to a variety of clients easily like browsers or mobile devices etc.

ASP.NET Web API Interview QuestionsBack to top

What are the advantages of using ASP.NET Web API?

Using ASP.NET Web API has a number of advantages, but core of the advantages are:

  • It works the HTTP way using standard HTTP verbs like GET, POST, PUT, DELETE etc for all CRUD operations.
  • Complete support for routing.
  • Response generated in JSON or XML format using MediaTypeFormatter.
  • It has the ability to be hosted in IIS as well as self-host outside of IIS.
  • Supports Model binding and Validation.
  • Support for OData.
  • and more….
For implementation on performing all CRUD operations using ASP.NET Web API, click here.70-486 Exam Preparation

Back to top

What new features are introduced in ASP.NET Web API 2.0?

More new features introduced in ASP.NET Web API framework v2.0 are as follows:

  • Attribute Routing
  • External Authentication
  • CORS (Cross-Origin Resource Sharing)
  • OWIN (Open Web Interface for .NET) Self Hosting
  • IHttpActionResult
  • Web API OData

You can follow a good Web API new feature details on Top 5 New Features in ASP.NET Web API 2 here.

Back to top

WCF Vs ASP.NET Web API?

Actually, Windows Communication Foundation is designed to exchange standard SOAP-based messages using variety of transport protocols like HTTP, TCP, NamedPipes or MSMQ etc. On the other hand, ASP.NET API is a framework for building non-SOAP based services over HTTP only. For more details, please follow here.
Back to top

Is it true that ASP.NET Web API has replaced WCF?

It’s a misconception that ASP.NET Web API has replaced WCF. It’s another way of building non-SOAP based services, for example, plain XML or JSON string etc.
Yes, it has some added advantages like utilizing full features of HTTP and reaching more clients such as mobile devices etc.
But WCF is still a good choice for following scenarios:
  • If we intended to use transport other than HTTP e.g. TCP, UDP or Named Pipes.
  • Messag Queuing scenario using MSMQ.
  • One-way communication or Duplex communication
A good understanding for WCF(Windows Communication Foundation), please follow WCF Tutorial.

Back to top

MVC Vs ASP.NET Web API?

As in previous ASP.NET Web API Interview Questions, we discussed that purpose of Web API framework is to generate HTTP services that reaches more clients by generating data in raw format, for example, plain XML or JSON string. So, ASP.NET Web API creates simple HTTP services that renders raw data. On the other hand, ASP.NET MVC framework is used to develop web applications that generates Views as well as data. ASP.NET MVC facilitates in rendering HTML easy.
MVC Vs Web API

For ASP.NET MVC Interview Questions, follow the link.
Back to top

How to return View from ASP.NET Web API method?

(A tricky Interview Question) No, we can’t return view from ASP.NET Web API Method. As we discussed in earlier interview question about difference between ASP.NET MVC and Web API that ASP.NET Web API creates HTTP services that renders raw data. Although, it’s quite possible in ASP.NET MVC application.
Back to top

How to restrict access to Web API method to specific HTTP Verb?

Attribute programming plays it’s role here. We can easily restrict access to an ASP.NET Web API method to be called using a specific HTTP method. For example, we may required in a scenario to restrict access to a Web API method through HTTP POST only as follows:
Restrict Access in Web API

Back to top

Can we use Web API with ASP.NET Web Form?

Yes, ASP.NET Web API is bundled with ASP.NET MVC framework but still it can be used with ASP.NET Web Form. It can be done in three simple steps as follows:

  1. Create a Web API Controller.
  2. Add a routing table to Application_Start method of Global.asax.
  3. Make a jQuery AJAX Call to Web API method and get data.
jQuery call to Web API for all CRUD (Create, Retrieve, Update, Delete) operations can be found here.

Back to top

How we can provide an alias name for ASP.NET Web API action?

We can provide an alias name for ASP.NET Web API action same as in case of ASP.NET MVC by using “ActionName” attribute as follows:

Web API Action Alias
Back to top

In this ASP.NET Tutorial, we covered most important Interview Questions on ASP.NET Web API framework. Hopefully, it will be helpful for Web API developer Interview but along with these questions, do the practical implementation as much as you can. In Practical guide to ASP.NET Web API, you can find a good step by step approach for understanding and implementing ASP.NET Web API services.

Previous <<< ASP.NET Interview Questions – Part -5

Other Related Articles:

Top 10 Interview Questions and Answers Series:

The post Top 10 ASP.NET Web API Interview Questions appeared first on Web Development Tutorial.

a MUST HAVE HTML5 Interview Questions and Answers – Part 2

0
0

It’s continuation of my previous post on HTML5 Interview Questions with detailed answers. In previous post we started to set a base knowledge for latest HTML standard i.e HTML5. Later discussing about HTML5 new elements and more details about Graphics related concepts including SVG and Canvas.

I’ll recommend to read the following posts on HTML5 Interview Questions:

Here we will continue exploring more HTML5 concepts with the help of Interview Questions.

HTML5 Interview Questions List – Part 2

What is a placeholder attribute in HTML5?

New placeholder attribute in HTML5 acts as a hint for input field value. It provides a kind of facilitating text for a description or expected type of value or an expected format of the value. For example, “Student Name” hints for a textbox expecting student name or “000-0000000″ hints for an expected phone number format etc.

<input type=”text” name=”studentName” placeholder=”Student Name” >HTML5 placeholder attributeplaceholder attribute is applicable to following input types:

  • text
  • password
  • email
  • url
  • search
  • tel

Back to top

What is a draggable attribute in HTML5?

In order to make an element draggable, HTML5 introduces draggable attribute. By default, Links and Images are draggable. If we want to make a paragraph or a span element draggable, will set the draggable attribute of that specific element to true as:

<span draggable=”true”>
Back to top

Is it possible to get the geographical location of a user using HTML5?

Yes. It’s quiet possible to get the geographical location of a user using HTML5. As it has user’s privacy concerns so user’s approval needed. As we discussed in previous post about new HTML5 API including Media API, Text Track API, Application Cache, User Interaction, Data Transfer API, Command API etc: HTML5 introduced new Geolocation API for locating a user’s position.

In order to get user position, getCurrentPosition() method is used as:

                  navigator.geolocation.getCurrentPosition(show_map);

Above code simply provides an idea how we can retrieve geographical location of a user. But while providing professional implementation, we will get user approval and also handle errors accordingly.HTML5 GeoLocation API
Back to top

What is Application Cache in HTML5?

HTML5 facilitates us to make offline version of complete or partial website contents including HTML files, JavaScript, CSS and images etc. Keeping an offline version speeds up site’s performance. Before HTML5, browsers were also caching contents but user’s have to visit all those HTML pages.
Back to top

How to enable Application Cache in HTML5?

In order to achieve Application Cache feature in HTML5, a manifest file is used as follows:

<!doctype html>
<html manifest=”test.appcache”>
…..
</html>

Manifest file is basically a text file that dictates what needs to be cache or not if Application Cache is enabled. Followings are the four main sections of a manifest file where CACHE MANIFEST is the only required section:

  • CACHE MANIFEST
  • CACHE
  • NETWORK
  • FALLBACK

HTML5 Application Cache ManifestBack to top

What is an HTML5 Web Worker?

Normally if some script is executing in an HTML page, the page remains unresponsive until the scripts execution stops. But an HTML5 web worker is a script (i.e. JavaScript) that keeps executing in background. At the same time user can interact with the page and will not feel any performance degradation.HTML5 Web Worker

HTML5 web worker normally exists in external files and used for long-running CPU intensive tasks but without affecting the User Interface or other scripts.
Back to top

What are the limitations of HTML5 Web Worker?

HTML5 Web worker seems to be very handy in many scenarios (especially for CPU intensive tasks) but it has certain limitations. Few JavaScript objects are not accessible to HTML5 web worker as:

  • parent object
  • window object
  • document object

Back to top

What is localStorage in HTML5?

In order to store data locally, HTML5 supports for localStorage object. It stores data for a longer time in a client browser but it doesn’t lost data even if browser is closed. This purpose was achieved previously with the help of Cookies.

localStorage has following advantages as compared to using Cookies:

  • localStorage has better performance even for larger amount of data.
  • localStorage can store data for longer period.
  • localStorage is more secure as compared to cookies.

Back to top

What about browser support for localStorage in HTML5?

Browser support for localStorage in HTML5 is as follows:

  • Chrome 4
  • IE 8+
  • firefox 3.5+
  • Safari 4
  • Opera 10.5

Back to top

Free Online Test


<<< Previous: HTML5 Interview Questions – Part 1

Other Related Articles:

Top 10 Interview Questions and Answers Series:

The post a MUST HAVE HTML5 Interview Questions and Answers – Part 2 appeared first on Web Development Tutorial.

Interview with Rahul Sahay –“ASP.NET MVC Code First”

0
0

I am excited to introduce my guest today, Rahul Sahay, Owner of a very active Technological Facebook group “ASP.NET MVC Code First“, a decent blog and Author of following books:

  • Hands-On with ASP.NET MVC Covering MVC6
  • Building Single Page App with ASP.NET MVC5 and AngularJS

Blog My View (http://myview.rahulnivi.net) which is nearing 1.5 Lac visits. 70K visitors visit site on regular basis. Facebook group members count reaching 13,000. Congratulations on that Rahul :)

Imran: Rahul, I have given a short introduction about you, your blog and books. Please tell us more about you and what you do?

Rahul: Thanks for kind introduction. Frankly speaking, last year when I started writing my blog; I started on 1st Jan 2014; that was last year resolution to spread the word. Later on I realized that people started liking my articles as my articles basically focus on How To stuffs? rather writing high level stuffs.

Imran: When did you start your Facebook group “ASP.NET MVC Code First”, and why did you create it? What was the motivation or inspiration behind it?

Rahul: Again, that get started last year to engage more people from same field. It’s like collect all the fishes from different ponds and put them in a single pond to have more engaging and interactive discussion on Facebook group.

Imran: What do you feel makes your Facebook group special?

Rahul: Hmmm. That’s a typical question. However, still with Facebook group long way to go as there are couple of groups on the top of this. But, special thing about this, we encourage people to cascade Job opportunities as well so that freshers/experienced people at the end get benefited.

Imran: What are some of the hot topics that seem to always be discussed within the group?

Rahul: Off course, MVC is the key thing. But, I also encourage people to talk about other technologies as well like AngularJS, WCF (Windows Communication Foundation), Web API, Entity Framework, Azure, Other JS testing patterns like Jasmine, QUnit and many more stuffs which is really hot cake in the market.

Imran: For someone new to this group, how do they get the most out of it?

Rahul: He/She need to be active not all the times. But, whenever they login, once check the discussion tab there, so that they will come to know latest happenings on the group.

Imran: For our audience, please discuss in detail about the books you have written?

Rahul: I start in a descending order. So, the latest one which I have written is actually marriage of tons client/server technologies.
Here, I have used technologies like ASP.NET MVC which is basically base framework for the application.

  • Web API:- Off Course in order to data transportation; I found Web API being the best. Since, it embraces stateless design out of the box and built in HTTP verbs support the same.
  • AngularJS:-This is one of the most talked technology in the neighborhood today. I find, Angular JS is the most suitable one for building SPA (Single-Page Applications).
  • QUnit:- This one I have used for testing my Web APIs. QUnit is one of the most popular JavaScript libraries used by JQuery team to write their test cases.
  • Jasmine:- Again, Jasmine is a different JS testing library used for writing test cases for AngularJS. I have chosen this one as angular team also uses the same one to write their test cases.
  • Unit of Work Pattern:- I am fan of this design technique. It always gives me ability to aggregate the changes or keep the changes at one place and use at multiple place.
  • Factory Pattern:- Under the hood of UOW, I am using factory pattern for initializing the factors like dbContext, off course, for the 1st time and then in subsequent call, it will be addressed by the same instance until site is closed.
  • Solid Principles:- SRP is one of the most used technologies from Solid principle. I usually keep my dependencies per class basis. This also helps me in writing clean Unit test cases.
  • Chutzpah Project:- This one I installed from Extension and Updates as this helps to integrate JS Test cases under the hood of MS Test runner. So, what will happen as soon as you click run all?, This will run both managed test cases and un-managed test cases under the same hood.

I have also written book on MVC. That is Hands-on with ASP.NET MVC. This basically talks about MVC right from the scratch till professional level Implementation.
Exam 70-486
Imran: Please discuss about your blog. What major areas are focused and how a developer can take maximum benefit from it?

Rahul: Frankly speaking I have started the blog as in for my learning purpose means as a online repository which I can refer at any point of time. But, later on I realized that people are coming to my blog and reading my article and providing feedback for the same. This actually boosted my confidence and then I decided, OK I will go ahead and make this a regular blog which will talk not only about Microsoft Technologies but discuss latest trend in the market like Angular. Till date, I think I have written 163 articles. And in about 1 year response is very good.

Imran: It’s really amazing Rahul. What are your future plans about introducing more exciting things for your group members? Also, Is there any specific topic you are planning to write a book about?

Rahul: Exciting thing to me is always talk about latest technology and share the same with group members. it’s very important to have the implementation knowledge at least on these new technology. Web is changing rapidly. People now converging towards JS framework more rather than managed code environment like .Net or Java. So, in future I’ll be talking more on ASP.NET 5 which is again a great change in this area and then off course Angular and Typescript. Also, I would like to focus on Azure and its capabilities. Next book which is coming is on WCF.
It is basically enterprise edition. So, here readers will experience end to end experience right from the scratch. Again this book is very deep dive. I think people will love it.

Imran: Finally, What do you suggest all your group members and .Net developers at large to improve their skills?

Rahul: Learning is important and learning new skills, new improvements of existing language like C#, and implementing the same in your existing project will help any person to improve the skills. This is very important because these days even client is very demanding, they don’t want to invest or focus on old stuffs.

Imran: Thanks a lot Rahul. I really feel proud to have you with us and sharing your thoughts. Thanks once again.


More You Must Read about ASP.NET MVC & Related

Top 10 Interview Questions and Answers Series:

The post Interview with Rahul Sahay – “ASP.NET MVC Code First” appeared first on Web Development Tutorial.

25 Best Tools for HTML5 Developers

0
0

Developers have been using HTML (HyperText Markup Language) for many years to develop the web pages. HTML5 is the latest version of HTML which has many new features to change the world of web development and design. The mobile internet user is growing at a faster pace across the world and therefore, it is a must for your website to have mobile responsiveness. HTML5 provides you with the feature to develop mobile-friendly websites. Being one of the most cost-effective languages for mobile applications, HTML5 has also enhanced the user experience largely. If you still want to know more, here is a list of advantages of HTML5 web development:

  1. Improved Accessibility
  2. Audio and Video Support
  3. Optimized and structured code
  4. Highly interactive websites
  5. Cross-browser compatibility
  6. Mobile responsive sites


This eventually leads to huge demand for professional HTML5 developers in the market. That being said, any new technology needs to be learned first in order to master it. Considering this fact, here is a list of the 25 best tools for HTML5 developers:

1. Animatron

Whether you are a newbie or a professional, Animatron lets you make your website highly interactive. And the best part is that you do not need to code. You just create your animations and save them on the cloud which can be accessed anytime and anywhere. Once, you have created your animation, you can export it to HTML5, GIF, and video formats. It is said that two heads always give better ideas, so you can invite your project team-mates to work on the same window by sharing the URL.
HTML5 Animation
You can watch all the changes as they are happening from the other side. In case, you do not want to share your project with anyone you can make it private. Choose a plan that suits you can go with one of the best tools.
LINK: https://www.animatron.com/

You can find a Comprehensive list of HTML5 Interview Questions and Answers here.

2. Purple Animator

Purple Animator is the best choice if you want to create designs for multiple platforms like Android, iOS, Kindle etc. You can create all the interactive app contents with the help of Purple Composer or, Purple Animator.

LINK: http://www.purplepublish.com/purple-animator/

purplepublish

3. INK

With the INK tool, you can create responsive HTML5 emails that can be accessed anywhere and on all devices or client including Outlook.

LINK: http://foundation.zurb.com/emails.html

ink

4. Initializr

It provides you with the templates from which you can choose and kick-start your project. You can also select the responsive template.

LINK: http://www.initializr.com/

Initializr

5. Create

It is a web-editing interface in which you can edit anything on Content Management Systems. It provides you a comprehensive HTML5 based environment in which you can edit any content you wish to and later you can push the changes to the CMS.

LINK: http://createjs.org/

create_js

6. HTML5 Maker

No other tool can win against HTML5 Maker when it comes to animations and web graphics. You do not need to create designs separately in Photoshop for the text or photos effects. HTLM5 Maker lets you do it all on one tool.

LINK: http://html5maker.com/#/

html5maker1

7. 99LIME

Joshua Gatcke runs this website to help the web designers learn creative web designing. You can learn tips and tricks of web designing to stand out of the crowd.

LINK: http://www.99lime.com/

99lime

8. HTML5 Bones

HTML5 Bones is a boilerplate for HTML5 websites. There are no JavaScript libraries included in it so it is very easy and basic to use.

LINK: http://html5bones.com/

HTML5 Bones

9. Mixeek

It is a web-based tool using which you can create interactive animations. It uses both HTML5 and CSS3. Not only this, it is also free and can be used easily.

LINK: http://www.mixeek.com/

mixeek

10. Edge Animate

It is a product by Adobe which is known for the best designing frameworks. With Edge Animate, you can create interactive HTML animations for web, digital publishing, rich media advertising etc. All these can be easily accessed on both web as well as mobile.

LINK: http://www.adobe.com/in/products/edge-animate.html

edge animation

11. Literally Canvas

Literally Canvas is an open-source HTML5 drawing widget. Using this extensible widget, you can do sketching and do anything with the end results.

LINK: http://literallycanvas.com/

12. RazorFlow

If you are looking for a tool to design Dashboards in PHP and JavaScript, then RazorFlow is what you need.

LINK: https://www.razorflow.com/

13. Onsen UI

Onsen UI is a custom elements based HTML5 UI framework that can be used for Cordova UI development. It enhances the user-experience and provides native-like performance.

LINK: http://onsen.io/

14. Google Web Designer

Create outstanding visual experience without worrying about the backend part with Google Web Designer. You can design creative HTML5 designs and can implement the same on any device.

LINK: https://www.google.com/webdesigner/

15. HTML Test

I am sure you would want to check the compatibility of your HTML5 with your browser. HTML Test checks your browser’s over functionality

LINK: http://html5test.com/

16. TUMULT

Tumult is also one of the apt choices for creating interactive web content and designs. It provides support on desktops, mobile devices and iPads. It provides you multiple browser support, CSS effects, ability to embed easily and you can also share it via Dropbox.

LINK: http://tumult.com/hype/

17. Stitches

You can create both sprite sheets and spreadsheets by just dragging and dropping the images on the tool. A sprite sheet is created by combining multiple small images or icon into a larger image. Try it yourself as it provides a demo.

LINK: http://draeton.github.io/stitches/

18. Sencha

Sencha is web application development platform. You can create n number of cross-platform applications that provides native-like user experience. After designing and developing the application, Sencha also gives you the power to manage the app yourself. You can first go with the free version and then get the premium one as per your requirement.

LINK: https://www.sencha.com/

19. Moqups

Next time you need to create designs, wireframes, prototypes or any UI concept; Moqups is the one solution for all. Simple drag and drop function makes this nifty HTML5 App highly usable.

LINK: https://moqups.com/

20. Mugeda

You can create HTML5 animations, cross-platform apps, analyze traffic, media campaigns and much more with this professional IDE i.e. Mugeda. It provides you with a Mugeda JavaScript API, using which you can create web or hybrid apps.

LINK: https://www.mugeda.com/

21. ShareDrop

ShareDrop is a clone of Apple AirDrop Service but in HTML5. This tool lets you share the files directly without the need of uploading them on the server.

LINK: https://www.sharedrop.io/

22. Cloak

If you are developing an HTML game, then Cloak is a must as it acts as a network stratum. It provides with features like resuming when reconnecting and timers.

LINK: http://incompl.github.io/cloak/

23. CutJS

For the cross-platform game-development use Stage.js which is open-source and lightweight HTML5 JavaScript library.

LINK: http://piqnt.com/stage.js/

24. Framework 7

It is an app development framework with you can create robust iOS and Android applications with the native look and feel. It uses HTML for the application development, therefore reducing the cost of development.

LINK: http://www.idangero.us/framework7/#.Vk21cnYrLIU

25. Puzzle Script

Puzzle Script is used to create complex puzzle games. It is an editor in which you can build the game, export it and share too.

LINK: http://www.puzzlescript.net/editor.html

With all these best tools you create the best websites or mobile applications for any purpose including gaming. Choose what suits you the best and then create the best solutions.

Author Bio:

Nirdosh has a knack for exploration and loves to dig into WordPress, and share her knowledge with others. She is currently working with WP Daily Themes. She is also a programmer, a writer and a motivational speaker.

Are you looking for a Web Development Jobs in Gulf Region? Please follow below:
Top Gulf Jobs

The post 25 Best Tools for HTML5 Developers appeared first on Web Development Tutorial.


Top 20 Entity Framework Interview Questions – MUST HAVE

0
0

This post is about Entity Framework Interview Questions that will explore various features, concepts and FAQs regarding Microsoft Entity Framework. It’s basically a collection of most frequently asked Entity Framework Interview Questions for developers. You can also explore some practical solutions implementing Entity Framework here:

You are working with WebDevTutorial and building an ADO.NET Entity Framework application for a client. You need to validate the conceptual schema definition language (CSDL), store schema definition language (SSDL), and mapping specification language (MSL) files. Which Entity Data Model tool can you use? (Each correct answer presents a complete solution. Choose all that apply.)
  • A. EDM Generator (EdmGen.exe)
  • B. ADO.NET Entity Data Model Designer
  • C. Update Model Wizard
  • D. Entity Data Model Wizard
  • E. All of Above
  • F. None of Above

For a complete online test and Practice Exams on Web Technologies, Click Here.

 Correct Answer: B, D

Entity Framework Interview Questions List

  1. What is Entity Framework?
  2. What are the advantages of using Entity Framework?
  3. What is the Nuget Package console command to install Entity Framework, if it’s not there in you project at that time?
  4. Where do we use Virtual classes in Entity Framework DbContext Models?
  5. Entity Framework uses DbContext, How is it different from Object Context?
  6. What’s new in Entity Framework 6?
  7. Can we access a model in Entity Framework without primary key defined?
  8. Why do we use Lazy Loading in Entity Framework?
  9. Why DB Context models object disposal is important in Entity Framework?
  10. Can we do an insertion and deletion at the same block of code and then Apply save changes to them in a statement in Entity Framework?
  11. What are the development approaches are supported in Entity Framework?
  12. What is the query syntax we use to query an ADO.NET Entity Data Model?
  13. Is LINQ a feature of Entity Framework?
  14. Does Default New Project Creation under Internet Template Category of ASP.NET MVC have any DB Context Ready while creating the project?
  15. If you provide the Primary Key value while inserting record to Entity Framework, will that execute fine, or will it throw an error while the adding statement?
  16. What are the properties or Database Elements get copied in Dataset when Clone method is used?
  17. What is the role of a Self-Tracking Entities?
  18. Can you describe the feature of split entity in Entity Framework?
  19. What is the role of Entity Container in Entity Framework?
  20. Do we need to define any assembly refinances of entity framework if we use in web.config file?

What is Entity Framework?

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

Microsoft introduced Entity Framework with .NET Framework v3.5 Service Pack 1 supporting basic Object Relational Mapping support but later EF4 was introduced as second version aligning with .NET Framework v4.0.
Back to top

What are the advantages of using Entity Framework?

Main advantages of Entity Framework are:

  • Separation of Concerns (SoC).
  • LINQ is used as a common syntax for all object queries.
  • Code Auto-Generation.

Back to top

What is the Nuget Package console command to install Entity Framework, if it’s not there in you project at that time?

Following is the Nuget Package console command to install Entity Framework:

Install-Package EntityFramework -Version 6.1.1Install Entity Framework -Version 6.1.1
Back to top

Where do we use Virtual classes in Entity Framework DbContext Models?

We use Virtual classes in Entity Framework in context class where we define DBSet of corresponding table. As we can see easily in below code sample for Students and Departments:
Entity Framework Interview Questions Virtual Classes
Back to top

Entity Framework uses DbContext, How is it different from Object Context?

DbContext can be used for code first while Object Context doesn’t. It exposes the most commonly used features of ObjectContext.
Back to top

What’s new in Entity Framework 6?

  • Customizing Code First Conventions.
  • Logging of database commands.
  • Stored Procedure Mapping.
  • Asynchronous Queries and Save support.

Whats New In EF6

With EF6, in applications with lots of tables and relationships defined, our context objects open faster. We should also be better insulated from dropped connections (at least, if the drop is transient and not permanent — nothing is going to help there).  EF6 also generates SQL faster from LINQ queries than before (though it’s the same SQL that’s being generated as in earlier versions of EF, so your actual data access won’t be any faster or slower).
Back to top

Can we access a model in Entity Framework without primary key defined?

No, but we can access data.

Using Primary Key:

Student student = db.Students.Find(id);

Without Primary Key:

Student student = db.Students.Where(x=>x.StudentName==”Ahmad”);

Back to top

Why do we use Lazy Loading in Entity Framework?

Entity Framework facilitates us to avoid huge, deep, highly-relational queries, so that the data will not heavy on the web.

Lazy Loading in Entity Framework
Back to top

Why DB Context models object disposal is important in Entity Framework?

Until it’s disposed, it will be holding resources that aren’t in. If not disposed then Garbage collector will free the space but in some instance it holds up.

Calling dispose method to clear memory.Dispose in Entity Framework
Back to top

Can we do an insertion and deletion at the same block of code and then Apply save changes to them in a statement in Entity Framework?

Yes, WE CAN by using the below piece of code:

Save changes in Entity Framework

Here the student record will insert to db but not physically. When we call SaveChanges method then it actually insert in db and commit the transaction. If we delete before committing transaction nothing will change in database.
Back to top

What are the development approaches are supported in Entity Framework?

  • Code First Approach – where code defines the database. Entity Framework handles creation.
  • Database First Approach – regular approach used where database is first created or already exists.
  • Model First Approach – where model is drawn first that further generate database scripts.

Development Approaches in Entity Framework
Back to top

What is the query syntax we use to query an ADO.NET Entity Data Model?

We can use LINQ to Query ADO.Net Entity Framework. For Example:

Entity Data Model
Back to top

Is LINQ a feature of Entity Framework?

Yes, following is the example to get student record from Section A.

LINQ feature in EF6

The same in Entity Framework:

Student student = db.Students.Where(x=>x.Section==”A”);
Back to top

Does Default New Project Creation under Internet Template Category of ASP.NET MVC have any DB Context Ready while creating the project?

Yes, There is, as we can see in the below screenshot:Template Category For MVC
Back to top

If you provide the Primary Key value while inserting record to Entity Framework, will that execute fine, or will it throw an error while the adding statement?

Yes it will threw error if same a record present with same data. If identity is set then it will give error in any case.Insert In EF6
Back to top

What are the properties or Database Elements get copied in Dataset when Clone method is used?

It will create a new object with same properties with a new instance.Clone Method in EF6
Back to top

What is the role of a Self-Tracking Entities?

Self-tracking entity allows you to add code generated item:Self Tracking Entities in EF6
Back to top

Can you describe the feature of split entity in Entity Framework?

Entity splitting gives us the ability to take an entity in our model and split this entity into multiple database tables. When we query an entity, Entity Framework will create a query that Automatically joins the related physical tables for us.
Back to top

What is the role of Entity Container in Entity Framework?

Entity container is a logical grouping of entity sets, association sets, and function imports.  The following must be true of an entity container defined in a conceptual model:

At least one entity container must be defined in each conceptual model.  The entity container must have a unique name within each conceptual model.

Entity Container in EF
Back to top

Do we need to define any assembly references of entity framework if we use in web.config file?

Yes, that is necessary:web.config for Entity Framework

Back to top

  • Learn ASP NET MVC 5 step by step [Maruti Makwana, Corporate Trainer] 28 Lectures, 2.5 Hours Video, Intermediate Level
    Very easy to learn video series on Asp.Net MVC 5 Specially for those who are familiar with Asp.Net Web forms.
  • AngularJS for ASP.NET MVC Developers [Brett Romero] 10 Lectures, 1 hour video, Intermediate Level
    The Fastest Way For .NET Developers To Add AngularJS To Their Resume
  • ASP.NET with Entity Framework from Scratch [Manzoor Ahmad, MCPD | MCT] 77 Lectures, 10 hour video, All Level
    Latest approach of web application development
  • Comprehensive ASP.NET MVC [3D BUZZ] 34 lectures, 14 Hours Video, All Levels
    From zero knowledge of ASP.NET to deploying a complete project to production.

Concluding Notes:

Again, this is my prepared list of important Entity Framework Interview Questions but reader can suggest/contribute more related concept area. I’ll be more happy to add those questions/concepts and update the Entity Framework Interview Questions list.

More Related Articles:

Top Interview Questions and Answers Series:

ASP.NET MVC Jobs [Updated Daily]

Top ASP.NET MVC Jobs

Web Application Developer
Source: Indeed
Details: Involving the development of an MVC based web application for a state agency. The ideal candidate will have extensive knowledge working with C#, ASP.NET, MVC,...  More
30+ days ago

Chantilly, VA 20151 16-June-2016

UI/UX Developer
Source: Indeed
Details: C#, Anjular, MVC, .NET:. Create effective, professional UI designs and implement them using ASP.NET, MVC and .NET....  More
19 hours ago

Overland Park, KS 28-July-2016

Sr .Net Developer
Source: Indeed
Details: ASP.NET, MVC, WEBAPI, C#, SQL SERVER:. This is a hands-on development position and as such, must be skilled in *C#, Asp.Net MVC, WEBAPI*....  More
1 day ago

Skokie, IL 27-July-2016

Junior .Net Developer
Source: Willis Towers Watson
Details: MVC experience preferred. You will also be responsible, to some extent, to maintain and customize our pre-BenefitConnect software, written in Visual Basic 6,...  More
16 days ago

Washington, DC 12-July-2016

Junior .NET Developer
Source: Hobby Lobby
Details: ASP .NET MVC Experience - preferably MVC 4 and the Razor view engine. We are in search of an enthusiastic and self-motivated C# developer with 2 to 4 years of...  More
30+ days ago

Oklahoma City, OK 73179 08-June-2016

C# / ASP.NET Developer (FTE) (Dallas)
Source: Brand Protection Agency, LLC
Details: The developer will be exposed to the latest technologies such as WCF, ASP.NET, ASP.NET MVC, .NET 3.5 and 4.0, JavaScript, AJAX, JSON, ext-js and other open...  More
1 day ago

Dallas, TX 28-July-2016

C# .NET Application Developer
Source: Norfolk Southern Corp
Details: C# ASP.NET, MVC, Java. 5+ years coding/developing using MVC, JQuery, AJAX, WCF, and Json. The Norfolk Southern Information Technology Department is currently...  More
1 day ago

Atlanta, GA 27-July-2016

Web Application Developer - C#/.NET
Source: Yankee Book Peddler
Details: ASP.Net MVC, CSS, jQuery, XSL, XSD, Ajax, Bootstrap, Knockout, WCF, windows services and console applications....  More
2 days ago

Contoocook, NH 27-July-2016

Web Application Developer - C#/.NET
Source: EBSCO Information Services
Details: ASP.Net MVC, CSS, jQuery, XSL, XSD, Ajax, Bootstrap, Knockout, WCF, windows services and console applications....  More
2 days ago

Contoocook, NH 26-July-2016

Senior .Net Developer
Source: Seminole County, FL
Details: Must be able to program with C#/.Net MVC applicants, classic ASP, visual basic .NET, html, CSS, Java Script, and scripting languages....  More
30+ days ago

Sanford, FL 08-May-2016

C# / .NET Application Developer - Frankfort, KY
Source: NTT Data
Details: Demonstrated understanding of C#, ASP.NET, MVC and Microsoft SQL Server. Strong experience with MVC Framework, Visual Studio, and Microsoft SQL Server....  More
3 days ago

Frankfort, KY 25-July-2016

.Net Developer
Source: Indeed
Details: *ONLY LOCALS* *TITLE: Programmer Analyst Sr/Ld* *PURPOSE STATEMENT: * Works independently to provide advanced technical analysis, and application systems...  More
23 days ago

Phoenix, AZ 05-July-2016

.Net Developer
Source: Indeed
Details: Visual Studio 2015/2013, ASP.NET, C#, MVC, WCF, SOAP and RESTful API, jQuery 9. Extensive familiarity with the .NET framework, ASP.NET, ASP.NET MVC, ASP.NET Web...  More
2 days ago

Orlando, FL 32801 26-July-2016

.Net Developer
Source: Indeed
Details: Hi, Please find below requirement for .Net Developer position. *Need profile with 10+ years of exp* *H1B Transfer is okay* *Interview - Immediate* ...  More
3 days ago

Nyack, NY 26-July-2016

Senior .Net Developer
Source: USM
Details: Strong proficiency in Web API 2.0 and ASP.Net MVC with some JavaScript framework, preferably Angular. Senior .Net Developer....  More
30+ days ago

King of Prussia, PA 22-April-2016

Jr .Net Developer - Programmer
Source: Indeed
Details: C#, ASP.NET MVC, SQL Server, and Visual Studio. PNW BOCES (Education Services) is seeking a full-time Jr....  More
7 days ago

Yorktown Heights, NY 10598 22-July-2016

.Net and Knockout Developer
Source: Indeed
Details: Web-based software development utilizing the Microsoft development toolset - C#, ASP.NET MVC 4 or other MVC web frameworks- HTML5, JavaScript, CSS- Proficiency...  More
9 days ago

Plano, TX 19-July-2016

.NET Developer
Source: Indeed
Details: Experience with ASP.NET WebForms, ASP.NET MVC. This position requires a full development stack experience including front end (HTML, CSS, and JavaScript),...  More
9 days ago

Reston, VA 19-July-2016

Mid-Senior level .NET Developer
Source: Jobspring Partners
Details: Job, Software, Software Development, Developer, Role, Opportunity, Position, Lead, Principle, Architect, Technology, Jobs in Boston, SW, SDLC, Web, Desktop, GIT...  More
30+ days ago

Chicago, IL 06-June-2016

Mid-Level ASP.NET / Front End Developer
Source: Indeed
Details: We're a small Pittsburgh based web development company looking for an additional developer to join our team. This position will have a chance to work on many  More
11 days ago

Pittsburgh, PA 18-July-2016

Sr.Net Developer, F2F Columbia, MD
Source: Indeed
Details: Knowledge of ASP.NET MVC. C# from scratch, MVC 5.0 preferred, 4.0:. C# from scratch, MVC 5.0 preferred, 4.0 is acceptable....  More
30+ days ago

Columbia, MD 22-June-2016

C# Developer
Source: Career Evolutions
Details: Understanding of MVC, and experience with ASP.NET MVC. Design, develop and maintain web-based applications to enhance the performance and reliability of our...  More
13 days ago

Irvine, CA 92618 16-July-2016

IT - Web Developer
Source: Indeed
Details: Minimum of 7 years of development experience with ASP.NET MVC; Please go thru the requirement and let me know if you would be interested, if so please share...  More
30+ days ago

Eden Prairie, MN 21-June-2016

Senior .NET Developer
Source: PeerSource
Details: 8+ years experience in C#/ASP.NET MVC development. AngularJS, Telerik Kendo MVC Controls or other third party controls....  More
3 days ago

Lafayette, CO 26-July-2016

Senior .Net Developer
Source: Workbridge Associates
Details: C#, ASP.Net, MVC, Web Services/WCF, JQuery, JavaScript. An international professional services company that provides a broad spectrum of client services...  More
2 days ago

Dallas, TX 26-July-2016

The post Top 20 Entity Framework Interview Questions – MUST HAVE appeared first on Web Development Tutorial.

Top 20 AngularJS Interview Questions – MUST HAVE

0
0

A comprehensive list of AngularJS Interview Questions and detailed answers that takes developer from entry-level to an experienced one by discussing core concepts with code samples. It’s not only helpful for an interview but also for developing professional AngularJS applications.

Below Web Development Tutorials will also be helpful to practically grasp the technology.

AngularJS Interview Questions List

What is AngularJS?What are the key features of AngularJS? Is there any down-side of using AngularJS?

AngularJS is an open-source JavaScript system grew by Google. It helps you to make (SPA)single-page
applications or one-page web applications that just require HTML, CSS, and JavaScript on the client side. In light of MV-* design, it allows us to build very much organized, effortlessly testable, and viable front-end applications. AngularJS has adapted the best approach to web advancement.
Through it we can easily bind model data to html element, build dynamic html element, make logical decision and do both accept or send data through RESTful API.Advanced AngularJs Interview Questions and Answers

Although all this think can be done through JQuery but with AngularJS we can do all those stuff structurally. That is we can maintain a development structure which required for enterprise web application development, for example, we can extend html’s syntax and build re-useable custom component.

There is no question, JavaScript systems like AngularJS, Ember and so on are the eventual fate of web development.

AngularJS Key Features: 

  • Two way data binding: It allows us to bind data dynamically to html element that come from application’s back-end and also synchronized html element’s data value with front-end model at run-time i.e. it provide the feature of two way data binding.
  • Directive: It allows us to build re-useable custom directives. Which can save lot of time when we build large scale web application. Also it provide lots of built-in directive out of the box such as ng-repeat, ng-if, ng-model, etc. So that we can easily build single page web application.
  • Web-Service: It provide built in support for building restful and soap web service.
  • Model-View-Controller: It support concept of mode-view-controller of modern web application developed.  Through $scope provider we can make model which can be blinded to the View (HTML), and through function and restful-service ($resource, $http, etc.) we can build controller in AngularJS.
  • Routing Service: It provide built-in routing facilities through $routeProvider service.
  • Dependency Injection:  It support the concept of dependency injection like J2EE web app and Spring framework.
  • Security: We can easily implements front-end resource access controlling mechanism through various out of box component of this framework.
  • Filter:    It provide various built-in filter to convert data to desired format for view purpose such as currency, date, lowercase, uppercase, etc.

AngularJS Disadvantages/Down-side:

As this framework built upon JavaScript which is not type safe language so when application grow it become difficult to maintain source code and also difficult to find out bugs in application. This framework run base on the principle of digest look which execute all the time behind the screen which some time slow down a simple process. Some feature of AngularJS framework does not support equally in all web browser.
Back to Top

What is AngularJS Boot Process? Explain in detail with diagram?

There are two ways to initialize AngularJS to our web application:

  1. Initialized AngularJS through DOMContentLoaded event of the Browser.
  2. Manually Initialized AngularJS by calling angular.bootstrap() methods of AngularJS framework.

1) Initialized AngularJS through DOMContentLoaded event of the Browser

To initialized AngularJS through DOMContentLoaded event of the browser, we need to add “ng-app” directive to any HTML element and load the angular.js script. For example:

<!doctype html>
<html>
 <body>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
      <div id="ngScope" ng-app="appModule">
          Do you necessary stuff with angular JS.
      </div>
 </body>
</html>

When we load this page in browser AngularJS initializes automatically when DOMContentLoaded event is fired that is when the initial HTML document has been completely loaded and parsed (any JavaScript in this case angular.js), without waiting for stylesheets, images, and subframes to finish loading, Then angular looks for the ngApp(i.e. ng-app) directive in this case div HTML element with id ngScope. This ngApp directive define our application root and the HTML element(in this case div with id ngScope) define the scope of the ngApp directive. If ngApp directive is found then Angular will do the following:

  • Load any module associated with the directive.
  • Create required application injector.
  • Compile the DOM that contain ng-app directive as the starting point of the compilation. This allows us to consider only a portion of the DOM (in this case div element with ngScope id) as an AngularJS application.

Below diagram show the overview of AngularJS bootstrap process:

angularjs boot process

2) Manually Initialized AngularJS by calling angular.bootstrap() methods of AngularJS framework

Through manual Initialization process we can have more control over the initialization process. In this case we need script loaders to define main app module and then as pre application requirement we can define controllers, services, directives, etc. via main app module.

<!doctype html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

<script>
    // first build custom main app module
    var customAppModule = angular.module('appModule', []);
    //add controller to the custom module
        customAppModule.controller('CtrlBoot',function ($scope) {
                $scope.name = 'World';
            });

        // Here we load the custom module to this page
        angular.element(document).ready(function() {
        angular.bootstrap(document, ['appModule']);
    });
</script>

<div ng-controller="CtrlBoot">
    Hello {{name}}!
</div>

</body>
</html>

Here we first create custom app module (appModule) then create the controller through this module.

Finally we load custom app module to the html DOM object by calling the angular.bootstrap() function. Note that here we pass the custom module name as second parameter of the method and must create this custom modules before we inject this as a second parameter of angular.bootstrap() function. To load controllers, services, directives, etc. we must define those before calling angular.bootstrap() function. We should not use the ng-app directive when we manually bootstrapping AngularJS application.
Back to Top

How MVC is represented in AngularJS?

Mode-View-Controller (MVC) is a design pattern. It can be represented in AngularJS framework as follow:

Model: Model in AngularJS is just a JavaScript object which contains properties either primitive such as string, integer, Boolean, array or complex type object. Its main responsibility to hold data that come from controller or service. Some time it also contains business logic which related to view.

View: It’s just a plain HTML page with embedded AngularJS directives and expression. In AngularJS we mainly represent model data through view.

Controller: It’s a JavaScript function which main responsibility to bind model data to view and vise-versa. It can also contains business logic through which it determine which model goes to which view. Controller also responsible for bind model data that come http request or other services.

We can graphically represent the MVC concept as follow:

Model View Controller

For example: Here we create a view with a customerInfoModel model and a CustomerInfoCtrl controller:

<!DOCTYPE html>
<html ng-app="angularMvc">
<head>
    <title>Customar information</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <script>
        //Here we define customer model
        var customerInfoModel = {
            name: "Sonia Yeasmin",
            address: "Dhaka, Bangladesh",
        };


        // Here we define main app module
        var appModule = angular.module("angularMvc", []);

                // Here we define controller and $scope object as function argument
        appModule.controller("CustomerInfoCtrl", function ($scope) {
            $scope.customerInfo = customerInfoModel;
        });

    </script>

</head> <!--Here we bind model data to the view through controller-->
<body ng-controller="CustomerInfoCtrl">
    Customer Name: <input type = "text" ng-model = "customerInfo.name">
    Address : <input type="text" ng-model = "customerInfo.address">
    <br>
    <div>
        <p>Two way binding of Customer Name and Address</p><br>
        <P>Customer Name: {{customerInfo.name}}</P>
        <P>Address: {{customerInfo.address}}</P>
    </div>
</body></html>

Above example we can see how customer model is blinded to view through controller. Through $scope object of AngularJS we implement two-way binding and here controller define visibility level of $scope object in the view, in this case the <body> element of the view.
Back to Top

What is routing in AngularJS? Explain in detail.

Routing is mechanism of mapping different URL request to different views of web application. We implement this functionality in AngularJS through $routeProvider.

Routing in AngularJS

As seen from the above diagram user enter a specific url into the web browser then $routeProvider load that specific web page into the web browser, it also load specific controller for that web page. We will implement this mechanism by coding as follow:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>AngularJS Routing Mechanism</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js"></script></head>
<body ng-app="routMechanism">

<a href="#/customerinfo">Customer Information</a><br/>
<a href="#/productinfo">Product Information</a><br/>
<a href="#/inventory">Inventory</a><br/>


<div ng-view></div> <!—router load the requested page content into this div element-->


<script>
    var appModule = angular.module("routMechanism", ['ngRoute']);

    appModule.config(['$routeProvider',function($routeProvider) {
            $routeProvider.when('/customerinfo', {
                templateUrl: 'customerinfo.html',
                controller:  'CustomerInfoController'
            });
            $routeProvider.when('/productinfo', {
                templateUrl: 'productinfo.html',
                controller: 'ProductInfoController'
            });
            $routeProvider.when('/inventory', {
                templateUrl: 'inventory.html',
                controller: 'InventoryController'
            });
            $routeProvider.otherwise({
                templateUrl: 'index.html'
            });
        }]);


/*for the sake of simplicity and illustration here we define three empty controller*/

       
    appModule.controller("CustomerInfoController", function($scope) {
    });
    appModule.controller("ProductInfoController", function($scope) {

    });
    appModule.controller("InventoryController", function($scope) {

    });

</script>

Here we load angular.js and angular-route.js script file. In the html <body> element we define ng-app module name that is routMechanism. Also here we include three hyper link through <a> which are related to customerinfo.html, productinfo.html and inventory.html page.

Next we include the ng-view directive inside the <div> element where the page content are loaded. In the main app module (appModule) we inject the ngRoute dependency. To set  up our routes we call the config method on the appModule object. The config method takes a function as its argument which is executed when the module is loaded but before the application is executed. The $routeProvider declared as a dependency to the function that is passed to the config method.

The $routeProvider is configured by calling the when() and otherwise() function. The when() function takes two parameter first one is the route path and the second one is a JavaScript object.  The route path is matched against the part of the given URL after the # when the application is loaded. The first parameter of when() function has is a JavaScript object which contains  two properties one is the templateUrl through which we set  which html page that the AngularJS should load and show inside  the <div ng-view></div> element, and through contoller property we load the specific controller for that page.

The otherwise() funciton execute when no route paths matchs with given url(In this case it load the index.html page).

[Note: The above configuration work like switch case of other programming language like C, Java,C#, etc.] Back to Top

What is Scope in AngularJS? Kindly explain briefly.

Scope is a built-in service (or JavaScript object $scope) of AngularJS framework. Through $scope, controller bind model data to their views. In AngularJS scope define the relationship between controllers and views. There are two ways to use $scope within controller.

  1. We can define data(model object).
  2. We can define behaviors which are JavaScript functions.

For example here we will create two $scope object with initial data and function and also show there visibility label in DOM hierarchy through two different controllers.

<!DOCTYPE html>
<html ng-app="scopeExample">
<head>
    <title>Scope Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <script>
        var appModule = angular.module("scopeExample", []);

        appModule.controller("CtrlFirst", function ($scope) {
            $scope.data = "initial date : 2016-09-10";
            $scope.getGMTDate = function () {
                $scope.data = new Date();
            }
        });

        appModule.controller("CtrlSec", function ($scope) {
            $scope.data = "John Abraham";
            $scope.inverseCase = function () {
                $scope.data = $scope.data.toUpperCase();
            };
        });
    </script>

</head>
<body>
<div id="first" ng-controller="CtrlFirst">
    <h4>First Controller</h4>
        <button type="button" ng-click=" getGMTDate()">
                Get GMT Date
        </button>
    <input ng-model="data">
</div>

<div id="second" ng-controller="CtrlSec">
    <h4>Second Controller</h4>
        <button type="button" ng-click="inverseCase()">
                Upper Case
        </button>
    <input ng-model="data">
</div>

</body>
</html>

To use $scope object in controller first we pass the $scope object to controller’s factory function. As seen here we define two controller CtrlFirst and CtrlSec. CtrlFirst controller’s $scope has a data property with initial value “initial date : 2016-09-10″ and a behavior define by getGMTDate()function.

Similarly CtrlSec contoller’s $scope has a data property with initial value “John Abraham” and inverseCase() function.

In view we bind the CtrlFirst controller within the <div id=”first”> element, so the $scope of CtrlFirst controller is only visible with in this <div> element. Similarly $scope of CtrlSec controller is only visible within the <div id=”Second”> element.

From the above example we can see visibility level of $scope object in AngularJS is limited within specific DOM, and with the help of controller we bind $scope value and behavior to that DOM (view element).

In AngularJS there is another type of scope which is $rootScope. This $rootScope is eventually become the parent of all $scope objects. The $rootScope object act like a global context in AngularJS application. That is there is only one $rootScope object for an ng-app module.
Back to Top

What are the Controllers in AngularJS? Explain briefly.

In AngularJS Controller is special function that created from factory function provided by AngularJS framework. The main function of a controller is to pass data and behavior of $scope object between view and model (which is JavaScript object that is blinded to $scope object). Through controller we also define the visibility of $scope object in view. It is simply act a glue between the view and the $scope’s model.

<!DOCTYPE html>
<html ng-app="mainAppModule">
<head>
    <title>Contoller Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <script>

        // Here we define the main application module
        var mainApp = angular.module("mainAppModule", []);

            // create ExampleController controller from factory method(controller) of AngularJS framework
            mainApp.controller("ExampleController",function ($scope) {
            //Here we define the customer info model
            $scope.customerInfo={};

            //define property to customerInfo model and initialized their value
            $scope.customerInfo.name="Rocky";
            $scope.customerInfo.address="Dhaka Bangladesh";
            $scope.customerInfo.monthlyExpense=0;

            //Here we define a behavior of customer info model
            $scope.customerInfo.getCustomerCategory = function (expense) {
                if(expense>5000){
                    //assign expense value to monthlyExpense property
                    $scope.customerInfo.monthlyExpense=expense;
                    alert("VIP Customer");
                }
                else{
                    //assign expense value to monthlyExpense property
                    $scope.customerInfo.monthlyExpense=expense;
                    alert("Normal Customer")
                }
            }
        });

    </script>
</head>
<body ng-controller="ExampleController">
<p>Customer Name: </p> <input  type="text" ng-model="customerInfo.name">
<p>Customer Address: </p> <input  type="text" ng-model="customerInfo.address">
<br><br>
Select Monthly expense:
    <select ng-model="customerInfo.monthlyExpense"
            ng-change="customerInfo.getCustomerCategory(customerInfo.monthlyExpense)">
        <option value="0">--Select--</option>
        <option ng-selected="customerInfo.monthlyExpense == '5000' "value="5000">VIP</option>
        <option ng-selected="customerInfo.monthlyExpense == '4000' "value="4000">NORMAL</option>
    </select>
<br>
<p>Monthly customer expense</p>
<span ng-bind="customerInfo.monthlyExpense"></span>
</body>
</html>

From the above source code we can see here we create an “ExampleController” controller through the factory method of AngularJS framework, and also define a customerInfo model and blind it to the $scope object. The customerInfo model has three property name, address, monthlyExpense and a getCustomerCategory (expanse) function which determine the customer type either VIP or NORML. Through getCustomerCategory function we can pass expanse value from view to the customerInfo model’s function with help of ng-model, ng-change directives and via “ExampleController” controller, based on the expanse value we can see alert message with customer information either VIP or NORMAL. Here we also bind the initial value of customerInfo model’s property to the view element with help of ng-model directive and controller. Here we see how $scope’s data exchange between model and view with help of controller and directives in AngularJS framework.
Back to Top

What are the Services in AngularJS? What is the role of services in AngularJS and name any services made available by default?

In AngularJS services are used to encapsulate functionality that we want to reuse in an application. We create a service when functionality doesn’t consider to be fit in a single problem scenario or building blocks rather than for a cross-cutting concern. In AngularJS we create service through service factory function within an application module and service is singleton objects that is it’s only created ones per application module and load in memory, when it is actually needed that is service in AngularJS follow lazy loading principle like other programming language JAVA, C#, etc.

The main role of services is to provide constant interface to communicate between different controllers of an application module and keep providing data until application module exist in memory.

By default there are many built-in services exist in AngularJS framework. For example:

  • $http: Service provides low-level access to the browser’s XMLHttpRequest
  • $resource: Provides support for working with RESTful APIs.
  • $location: Provides a wrapper around the browser location object.
  • $window: Provides a reference to the DOM window object.

You can find a complete list of built-in services check the link below:

https://docs.angularjs.org/api/ng/service
Back to Top

What are expressions in AngularJS? Explain briefly with example.

In AngularJS expression use to bind model data to view (html page). We write expression inside double braces likes {{expression}}. It is a type of one way data communication that is, data only come from model to view not vise-versa. Some important points to be noted while using expression which are:

  • Expressions are not evaluated against the global window object; instead, they are evaluated against a scope object.
  • We cannot use conditionals, loops, or exceptions. This is a good thing; we don’t want complex logic inside expressions.
  • We don’t get the usual ReferenceError or TypeError when trying to evaluate undefined properties. AngularJS expressions are forgiving in that regard.
<!DOCTYPE html>
<html ng-app="mainAppModule">
<head>
    <script src="angular.js"></script>
    <script>
        // Here we define the main application module
        var mainApp = angular.module("mainAppModule", []);

        mainApp.controller("ExpressionExample",function ($scope) {
            //Here we define the customer info model
            $scope.customerInfo={};
            //define property to customerInfo model and initialised their value
            $scope.customerInfo.name="Rocky";
            $scope.customerInfo.address="Dhaka Bangladesh";
        });
    </script>
</head>

<body ng-controller="ExpressionExample">
    <p>Customer Name: {{customerInfo.name}} </p>
    <p>Customer Address: {{customerInfo.address}} </p>
</body>
</html>
As seen for above example code, here we define a customerInfo model which has two property name and address with initialized value. In <body> element of the view we show those two property value through expression.
Back to Top

What are Directives in AngularJS? Explain ng-app, ng-init, ng-controller, ng-model, ng-bind, ng-repeat, ng-include, ng-disabled, ng-show, ng-hide, ng-click.

Directives in Angular JS are essentially JavaScript functions that are executed when the DOM is compiled by the Angular JS framework. Directives allow us to extend HTML element to create new HTML elements and it helps us to create foundation for rich and complex web applications in a way that is naturally expressive.

  • ng-app: This directive define the starting point of AngularJS application and also auto-bootstrap the application.
  • ng-init: This directive allows us to execute expression in the current scope, it also use to initializes properties of $scope variable.
  • ng-controller: Through this directive AngularJS support MVC design pattern and define scope of controller in view element.
  • ng-model: This directive use to bind input data from view to model object and vice-versa. Through this directive we can implement two-way communication between the model and view.
  • ng-bind: This directive use to bind model data to view. It represent one-way data binding.
  • ng-repeat: This directive generate dynamic elements on which it is applied, and also populate the generated contents for each object or values, in a collection. Its work like a loop of other languages such JAVA, C#, etc.
  • ng-include: This directive use to include external html page to the current html page.
  • ng-disable: This directive use to inactive an html element and it is do so by evaluation an given expression, if the given expression evaluate to true then the html element will be inactive; that is we cannot interact with that html element.
  • ng-show: This directive use to hide or show an html element, and it do so by evaluation an given expression, if the given expression evaluate to true then the html element will be shown, otherwise hide.
  • ng-hide: This directive use to hide or show an html element, and it do so by evaluation an given expression, if the given expression evaluate to true then the html element will be hiden, otherwise shown.
  • ng-click: This directive use to capture the click event of html element such as button, select, anchor ,etc. and allow us to bind functions on that event.

Back to Top

What is the difference between ng-show/ng-hide and ng-if directives?

The main difference between ng-show/ng-hide and ng-if directives are that; based on given boolean expression ng-if completely remove (if the expression evaluate to false) or recreate (if the expression evaluate to true) the html element i.e. DOM element dynamically on which ng-if directive applied.

On the other hand ng-show/ng-hide directives not remove or recreate html element i.e. DOM element dynamically, its only hide or show the html element by changing display visibility property dynamically through CSS on which ng-show/ng-hide directives applied.

So it better to use ng-if directive on html element; in such a case, when that html element contain less nested child html elements, so that remove or recreation DOM element take less time and performance of the page response not hurt.

On the other it is better to use ng-show/ng-hide directive on html element;  in such a case, when  that html element contain more nested child html elements, so that just changing the visibility of html element is better than removing that complete html element.
Back to Top

More AngularJS Interview Questions and Answers

What are Filters in AngularJS? Briefly explain uppercase, lowercase, currency filters.

In AngularJS filters transform data that goes from the scope object to the directive but don’t change the source data format. That is it, allowing us transform data only for display in views. Filter is applied to an expression by using (|) pipe operator followed by the filter name.

For example following code, show the use of uppercase, lowercase and currency filter in AngularJS:

<html ng-app="appModule">
<head>
    <title>Filters Example</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <script>
        angular.module("appModule", [])
                .controller("CtrlFilter", function ($scope) {
                    $scope.customerInfo = [
                        { name: "Tuli", address: "India", income: 50000 },
                        { name: "Rony", address: "Bangladesh ", income: 60000}
                    ];
                });
    </script>
</head>
<body ng-controller="CtrlFilter">
    <table>
        <thead>
        <tr>
            <td>Name </td>
            <td>Address </td>
            <td>income</td>
        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="cus in customerInfo">
            <td>{{cus.name    | uppercase}}</td>
            <td>{{cus.address | lowercase}}</td>
            <td>{{cus.income  | currency }}</td>
        </tr>
        </tbody>
    </table>
</body>
</html>

Here we define customerInfo array which contains two customer objects; and each object has name, address, and income property. We have used the ng-repeat directive to generate rows in a table element to display the each customer objects. While displaying customer name property we pass it through uppercase filter as {{cus.name | uppercase}}, similarly address property pass through lowercase filter as {{cus.address | lowercase}} and finally we pass the income property through currency filter as {{cus.income | currency}}.

Because of uppercase filter all customer name shown in upper case letter; similarly address shown in lower case letter and because of currency filter a $ sign appended before the income value. The default currency symbol is $, but we can specify an alternative as {{cus.income | currency: “£”}} in this case British pound symbol will appended before the income value. That is after the colon (the: character) we can specify our desired the symbol that we want to express.
Back to Top

How to make an AJAX call in AngularJS? Please explain and provide an example code for making a real-time AjAX call.

In AngularJS we can use $http or $resource to make Ajax call.  For example here we will use $http service to make an Ajax call in AngularJS.  For in this example we well use a student information text file which contain json format data of some students.

Content of studentInfo.txt file.
[
   {
      "studentFullName" : "Ahmad",
      "studentId" : 101,
      "marks" : "56"
   },

   {
      "studentFullName" : "Hamza",
      "studentId" : 102,
      "marks" : "48"
   },

   {
      "studentFullName" : "Ali",
      "studentId" : 103,
      "marks" : "80"
   },

   {
      "studentFullName" : "Saad",
      "studentId" : 104,
      "marks" : "56"
   }
]

By making Ajax call we will fetch the content of the studentInfo.txt file as follow:

Content of AjaxCall.html file.

<html ng-app="mainModuel">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <title>Ajax Call</title>
    <script>
        var appModule = angular.module("mainModuel",[]);
        appModule.controller("CtrlStudentInfo",function ($scope, $http) {
            var urlPath = "studentInfo.txt"

            $scope.count=0;
            $scope.IncrementCount= function () {
               $scope.count++;
            }

            $http.get(urlPath).success( function(response) {
                $scope.studentInfo = response;
            }).error(function (ObjectError) {
                console.log("Problem in fetch data from the given URL path please check the error object info: " + ObjectError);

            });
        });

    </script>
</head>
<body>
<h2>Student Info</h2>
<div ng-controller = "CtrlStudentInfo">

    <table>
        <tr>
            <th>Student Full Name</th>
            <th>Student ID</th>
            <th>Marks</th>
        </tr>

        <tr ng-repeat = "student in studentInfo">
            <td>{{ student.studentFullName }}</td>
            <td>{{ student.studentId }}</td>
            <td>{{ student.marks }}</td>
        </tr>
    </table>

    <button name="btnclick" ng-click="IncrementCount()">
        Call me
    </button>
    <p>{{ count }}</p>

</div>

</body>
</html>

[Note: To run this AjaxCall.html file in browser, we must have to put both AjaxCall.html and studentInfo.txt file in the same folder]

In the above example code we inject the $scope and $https service object into the controller, and in controller we first set url path of studentInfo.txt file then we pass that url path to the $http service’s get () method and call this method. This method return $http service object as a result, so we can chain success () callback method, which have an input parameter, that represent http response object of this Ajax call. If the get () method call is successful then the success () method will be called and bind the http response object to the studentInfo object. Finally we pass this studentInfo object to the view through $scope object and dynamically generate the student information in a table through ng-repeat directive, here success () method also return $http object as result, so we chain the error () callback method also.

However if get () method of $http service fail to fetch data from given url path then error () method will be called and print the error object’s information into the browser’s console.

Because it is an Ajax call so whatever the result of get () method and how much time it take to fetch data from text file, the browser page will be responsive all time, so that we can interact with the AjaxCall.html page while the $http.get () method is being working in background. So we click the Call me button any time to increment count value.
Back to Top

Explain two-way databinding in AngularJS with an example? Kindly provide appropriate details. Also explain the difference between one-way binding and two-way binding?

Two-way databinding in AngularJS refers to the mechanism in which we can synchronously change data between view and model, that is if we change data in view that change will be reflected in model instantly similarly if we change data in model that change reflect in the view instantly. That is we can modify data at both end; view and model.Two-Way databinding in angularjs

Above diagram show the working principle of Two-way data binding. While in One-way data binding; we can change data only at the one end (model) and other end (view) only reflect change.

One-Way Databinding

Above diagram show the working principle of One-way data binding, where we can only modify data in model, and that change will be reflected in view, here we cannot change data from view, which is main difference between one-way and two-way data binding.

In the following coding we implement two-way as well as one-way data binding as follow:

<!DOCTYPE html>
<html ng-app="appModule">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <script>
        var mainModule = angular.module("appModule",[]);
        mainModule.controller("CtrlDataBinding", function ($scope) {
            $scope.customerInfo = {};
            $scope.customerInfo.name = "Raid Islam";
            $scope.customerInfo.address = "Dhaka, Bangladesh"
        })
    </script>
</head>

    <body ng-controller="CtrlDataBinding">
        <h1>Customer Information</h1>
        <!--One-way data binding-->
        <strong>Name:</strong> {{customerInfo.name}}<br />
        <strong>Address:</strong> <span ng-bind="customerInfo.address"></span><br />

        <br />
        <!--Two-way data binding -->
        <label>We can set customer name: <input type="text" ng-model="customerInfo.name"/></label><br /><br>
        <label>We can set customer Address: <input type="text" ng-model="customerInfo.address"/></label>
    </body>
</html>

Here we create the customerInfo model with two property name and address. We initialized those two property in controller. In the view i.e. the <body> element of html page, we bind those property of the customerInfo object. First we implement one-way binding through expression {{}} and ng-bind directive.  Then we implement two-way binding through ng-model directive with help of <input> html elements.
Back to Top

How to validate data in AngularJS? Briefly explain with an example and source code.

Usually we take data from user through <form> element and submit data to the server (back-end) of web application also through form. Because <form> element of html allows us to validate data that taken from the user. AngularJS allows us to validate data of <form> element of html by providing some built-in form properties as describe in the following table:

Property

Description

$pristine Return true. If user has not yet start interacting with form element. Otherwise return false.
$dirty Return true. If user has already modify some form element’s data. Otherwise return false.
$valid Return true. If all elements of the form contains valid data. Otherwise return false.
$invalid Return true. If at least one element of the form contains invalid data. Otherwise return false.

For example consider the following HTML code:

<!DOCTYPE html>
<html  ng-app="mainValidationModule">
<head>
    
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
    <script type="application/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>


    <script>

        var mainValidationModule = angular.module('mainValidationModule', []);
        mainValidationModule.controller('CtrlCustomerFormValidation', function($scope) {

            $scope.customerInfo = {};
            $scope.customerInfo.fullName="";
            $scope.customerInfo.address="";
            $scope.customerInfo.income = 0;

            $scope.nameSpan = false;
            $scope.addressSpan = false;
            $scope.incomeSpan= false;
            
            $scope.submitForm = function(isValid) {

                // check form validity
                if (isValid) {
                    alert("Form contains valid data and ready for submit to server");
                }else {
                    if(!$scope.customerInfoForm.fullName.$valid)
                        $scope.nameSpan = true;
                     else
                        $scope.nameSpan = false;

                     if(! $scope.customerInfoForm.address.$valid)
                        $scope.addressSpan = true;
                     else
                         $scope.addressSpan = false;

                     if(!$scope.customerInfoForm.income.$valid)
                        $scope.incomeSpan = true;
                     else
                         $scope.incomeSpan = false;
                    alert("Form contains invalid data");
                }
            };
        });
    </script>
</head>

<body ng-controller="CtrlCustomerFormValidation">

<div class="container">
    <div class="col-sm-6 col-sm-offset-1">
       <h1>Form Validation</h1>
        <form name="customerInfoForm" novalidate ng-submit="submitForm(customerInfoForm.$valid)">
            
            <div class="form-group" ng-class="{'has-error': customerInfoForm.fullName.$invalid}">
                <label>Customer Name</label>
                <input type="text" name="fullName" class="form-control" ng-model="customerInfo.fullName" required>
                <span ng-show="nameSpan">Please enter a value Customer Name</span>
            </div>
            
            <div class="form-group" ng-class="{'has-error': customerInfoForm.address.$invalid}">
                <label>Customer Address</label>
                <input type="text"
                       name="address"
                       class="form-control"
                       ng-model="customerInfo.address"
                       ng-minlength="3"
                       ng-maxlength="50" required>
                <span ng-show="addressSpan">Address must between 3 to 50 characters</span>
            </div>

            <div class="form-group" ng-class="{'has-error': customerInfoForm.income.$invalid}">
                <label>Customer Income</label>
                <input type="number"
                       name="income"
                       min="0"
                       max="1000000"
                       class="form-control"
                       ng-model="income" required>
                <span ng-show="incomeSpan">Enter a valid number between 0 to 1000000</span>
            </div>
            
            <button type="submit" class="btn btn-primary">Submit Information </button>
        </form>
    </div>
</div>
</body>
</html>

In this above example code we include bootstrap style by providing cdn link. Here in controller of mainValidationModule module we define a customerInfo object which contains three properties fullName, address and income. In the view we make two-way binding of all three properties within <form> element and set it name attribute as name=”customerInfoForm ; and also include novalidate attribute to prevent default browser validation, this is not AngularJS directive, it is a standard HTML attribute.

Here we include required attribute to all three <input> element to make all property value mandatory for form submission. Here we also include <span> element below, to the all three <input> elements; to shows hints when a specific <input> element not have valid data; in this case the value of address property must between 3 to 50 characters and we make it possible through ng-minlength=”3″ and ng-maxlength=”50″ directives. Similarly customer’s income property value must between between 0 to 1000000 and here the input type is number. In all three <input> elements we apply has-error class base on input validity;

We determine input validity with help of customerInfoForm attribute and $invalid property of AngularJS; when we submit the form by clicking Submit Information button, submitForm() method get called. In this method we pass customerInfoForm.$valid expression as a parameter which represent a boolean value.

If the customerInfoForm.$valid expression evaluate to true then we can say all input element have valid data; that we check in the controller by give alert message; and if the customerInfoForm.$valid expression evaluate to false, then we find out which <input> element contains invalid data by evaluating “$scope.customerInfoForm.input_element_name_attribute_value.$valid” expression  which return boolean value. Base on this boolean value we show specific <span> element to provide hints to the user about the <input> element contains invalid data, by set the value of that specific ng-show directive to true.
Back to Top

What is deep linking in AngularJS? Explain in detail by providing an example.

Deep linking is process of encoding page state, such as the state of radio button, check box or the window’s current scroll position in URL. In AngularJS $routeProvider service provides a convenient interface for implementing deep linking by modifying the current URL without reloading the page.

For example, consider the URL: http://www.google.com/foo?bar=baz#qux. The three portions of a URL that we need to be familiar with are the path: /foo; the query string after ’?’ symbol: bar=baz; and the hash string after ‘#’ symbol: qux. The path and query string communicate with the server to locate precise resource we are looking for. Changing the path or the query string triggers a page reload in modern browsers. However, the browser does not send the hash portion to the server; thus, we can modify the hash component without triggering a page reload. The hash portion is typically used for deep linking functionality. For example consider the following html page:

<!DOCTYPE html>
<html ng-app="deepModule">
<head>
    <!--cnd provider-->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
    <!--cnd provider-->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.28//angular-route.min.js"></script>
    <script>
       var appModule = angular.module('deepModule', ['ngRoute']);
            /*define routing mechanism*/
            appModule.config( function($routeProvider) {
                    $routeProvider
                            .when('/pagefirst', {template: '<div><h2>Child page</h2><br>Content of the first page</div>'})
                            .when('/pagesecond', {template: '<div><h2>Child page</h2><br>Content of the Second Page</div>'});
                });
    </script>

    <title>Angular JS deep linking example</title>
</head>
<body>
<h1>Parent page</h1>
    <div>
        <a href="#/pagefirst'">First</a> | <a href="#/pagesecond'">Second</a>
        <hr/>
        <div ng-view>

        </div>
    </div>
</body>
</html>

Here the content of URL before # remain same regardless of whether we clicking hyperlink <a> First or Second. Only portion of URL after # get changed and no page reloading happening; only portion of the page that related to hyperlink get updated.
Back to Top

What is an interceptor? What are common uses of it?

Interceptors are AngularJS’s most flexible method for defining application‐level rules (security purpose) for handling HTTP requests. Suppose we wanted to attach the HTTP response status to the body of every HTTP response or we want to determine whether incoming HTTP request is valid or not. We can do this easily by using $httpProvider service provider; by implementing the concept of interceptor.

For example here we will use $httpProvider provides to implement interceptor functionality; for this example we need a json file productInfo.json, which will contains following data.

Content of productInfo.json file:

[ { "productName": "Apples", "type": "Fruit", "pricePerPiece": 1.20},
  { "productName": "Salmon", "type": "Fish", "pricePerPiece": 17.93},
  { "productName": "Trout", "type": "Fish", "pricePerPiece": 12.93 }]

Define the interceptor.html file as follow:

<!DOCTYPE html>
<!--define main -->
<html ng-app="interceptorModule">
<head>
    <title>Interceptor Example</title>
    <!--cdn link for angularjs framework-->
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>

    <script>
       var interceptorModule = angular.module("interceptorModule", []);
       var interceptorFunctions=function () {
           return {
               request: function (configObject) {
                   configObject.url = "productInfo.json";
                   return configObject;
               },
               requestError: function(configObject) {
                   console.log(configObject);
                   return configObject;
               },
               response: function (responseObject) {
                   console.log(responseObject);
                   return responseObject;
               },
               responseError: function(responseObject) {
                   console.log(responseObject);
                   return responseObject;
               }
           }
       };

       /*configure config function*/
       interceptorModule.config(function ($httpProvider) {
            $httpProvider.interceptors.push(interceptorFunctions);
        });
       /*here we define controller*/
       interceptorModule.controller("CtrlInterceptor", function ($scope, $http) {
            $scope.loadItems = function () {
                $http.get("no_existence_of_file.json").success(function (responseObject) {
                    $scope.products = responseObject;
                });
            }
        });
    </script>
</head>
<body ng-controller="CtrlInterceptor">
            <table >
                <thead>
                    <tr>
                        <th>Product Name</th>
                        <th>Type</th>
                        <th>Price</th>
                    </tr>
                </thead>
                <tbody>
                    <tr ng-repeat="productInfo in products">
                        <td>{{productInfo.productName}}</td>
                        <td>{{productInfo.type}}</td>
                        <td>{{productInfo.pricePerPiece | currency}}</td>
                    </tr>
                </tbody>
            </table>
            <p><button ng-click="loadItems()">Load Data</button></p>
        </div>
    </div>
</body>
</html>

[Note: To run this interceptor.html in browser we must put both interceptor.html and productInfo.json file in same directory.]

As in the preceding code, HTTP interceptors are defined as an array on the $httpProvider provider. Because providers can only be accessed in config () functions, interceptors must be defined in a config () function. Usually we insert factory functions that return objects with properties such as request, response, requestError, responseError.

But in this case, we define interceptorFunctions() function that return object which contains all the above properties and pass this $httpProvider.interceptors.push() method.

The function we have assigned to the request property illustrate how an interceptor can change a request by changing the requested URL to productInfo.json file, here we do not consider what was passed to the $http service method. To do this, we just change URL property of the config object and return this object as result so that it can be passed to the next interceptor.

For the response interceptor, we just print responses object data to the browser’s console; that we received from the server. We can also do other stuff with this object that received from server before sending it to the browser.

To complete this topic here we introduce the responseError property interceptor function which will be called when previous response interceptor throws an error.

And requestError property interceptor function which will be called when the previous request interceptor throws an error.
Back to Top

What is template in AngularJS? How would we programmatically change the template of a directive?

In AngularJS templates allows us to including external HTML into our currently loaded page in browser. The ngInclude directive is the simplest way to utilize client‐side templating. This directive enables us to replace the associated Document Object Model (DOM) element’s inner HTML with a given template’s HTML.

For example below the customerInfoTable.html file, which will act like template and will be included in the main page with the help of ngInclude directive.

Content of customerInfoTable.html file:

<table class="table">
    <thead>
    <tr>
        <th>#</th>
        <th>Customer Name</th>
        <th>Address</th>
        <th>Income</th>
    </tr>
    </thead>
    <tr ng-repeat="customer in customerInfoList" ng-class="$odd ? 'odd' : 'even'">
        <td>{{$index + 1}}</td>
        <td>{{customer.customerName}}</td>
        <td>{{customer.address}}</td>
        <td>{{customer.income}}</td>
    </tr>
</table>

Content of ngIncludeExample.html file:

<html ng-app="mainModuleOfTemplate">
<head>
    <title>Example of Templating</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
    <!-- CDN Link of Latest compiled and minified CSS  -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

    <script>
        var mainModuleOfTemplate=angular.module("mainModuleOfTemplate", []);
        mainModuleOfTemplate.controller("CrtCustomerInfo", function ($scope) {
                    $scope.customerInfoList = [
                        { customerName: "Tuli", address: "Dhaka Bangladesh", income: 45000 },
                        { customerName: "Rana", address: "Dhaka Bangladesh",  income: 60000},
                        { customerName: "Gomas", address:  "Dhaka Bangladesh", income: 80000},
                        { customerName: "Soton", address:  "Dhaka Bangladesh",  income: 25000}];
                });
    </script>
</head>
<body>
<div class="panel" ng-controller="CrtCustomerInfo">
    <h3 class="panel-header">Customer Information</h3>
    <ng-include src="'customerInfoTable.html'"></ng-include>
</div>
</body>
</html>

[Note: To run the ngIncludeExample.html fine in browser we must put both ngIncludeExample.html and customerInfoTable.html in same folder]

In the controller of ngIncludeExample.html file we define a customerInfoList which contains some customer information and we represent this information to the view through help of ngInculde directive by loading the customerInfoTable.html file. Furthermore, the ngInclude directive caches templates by their URL, so a given template is only loaded from the server once; and it also support lazy loading.

We can programmatically change the template of a directive by using the advanced compile and transclude settings. AngularJS directives’ transclude setting and its corresponding ngTransclude directive exist to reference external HTML code from within our directive’s HTML template. In other words, transclusion allows us to parameterize our directive’s template, enabling us to modify some HTML in the template based on our needs.

For example consider the html code below which dynamically change template of a directive:

<!DOCTYPE html>
<html ng-app="appModule">
<head>
    <title>Transclusion  Example</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js">
    </script>
    <script>
        var module = angular.module('appModule', []);
        module.directive('ngGreeting', function() {
            return {
                restrict: 'E',
                transclude: true,
                scope: {},
                template:
                    'This is example of dynamic template loading in directive ' +
                    '<span ng-transclude></span>',
            };
        });
    </script>
</head>

<body ng-init="initialValue = 'Welcome to the world ng-transclude of angularjs';">
    <ng-greeting>
        {{ initialValue }}
    </ng-greeting>
</body>
</html>

As seen from the above code now we have a directive with a parameterized template. AngularJS update any HTML we put into the directive element into the directive’s template.

What IDEs you can use for AngularJS development?

AngularJS development can be done with the help of following IDEs:

  • Visual Studio 2012, 2013, 2015 or higher.
  • Eclipse
  • WebStorm
  • Sublime Text
  • TextMate

Back to Top
These web developer interview questions are really helpful for performing good in an angularjs interview as well as enhances their technical skill with the help of plenty of concepts, examples and sample code.

Good luck for your AngularJs Interview :)

Learn Professional Web Development in AngularJS while building 10 unique Web Apps.
77 lectures, 14.5 Hours Video, All Levels
  • Your First Angular Website
  • Web Template Store
  • myContacts App
  • ngSocial Facebook App
  • Job Directory
  • KnowledgeBase
  • User Authentication App
  • Instagram Gallery
  • PubNub Chat
  • AutoFind

And also we will find Quiz at the end of each application to verify the skill improvement.

More Web Developer Interview Questions:

The post Top 20 AngularJS Interview Questions – MUST HAVE appeared first on Web Development Tutorial.

Top 15 Bootstrap Interview Questions – MUST HAVE

0
0

Bootstrap is undoubtedly very demanding mobile ready web development framework that helps developers build professional responsive website. This list of Bootstrap Interview Questions will help to grasp the technology easily as it contains lots of practical real-world examples with source code. These Bootstrap Frequently Asked Questions list is designed in a way that it takes reader from beginner level to more advanced questions in a flow.

Soon you will be able to get Bootstrap Interview Questions and Answers PDF here.

If you are further interested to see more practical implementations using Bootstrap, read the below ones also.

Bootstrap Interview Questions List

What is Bootstrap? What are the core features of Bootstrap? Why to use bootstrap for building websites.

Bootstrap is collection of compiled CSS files (less), HTML files, Typography (type of art work) and some supporting JavaScript files which is use to design modern websites. It act like a framework for front-end development of modern web application. It is open-source framework originally develop by Mark Otto and Jacob Thornton at Twitter.Bootstrap Framework

Following are the core features of Boostrap:

  • Through it we can design responsive web page that is a single page work for all type display device (PC, Tablet or Mobile) and with different resolution.
  • With Boostrap framework, get out of box many built-in component such as Dropdowns, Styled Button, Navigation bar, breadcrumbs, Labels & Badges, alerts, Progress bar, etc. which help us to design responsive web site.
  • It allow us to build page with grid system that divides page space equally which scale up to 12 columns.
  • As a part of Framework, we get lots of JavaScript plugins through we can achieve most common tasks such as sliders, tabs, accordions, modal windows, etc. can be build more easily rather than integrating third party plugins.
  • As it is an open source framework, so we can customized the core component as we need without considering about license.
  • Also this framework is well documented, describing every component and their example use are well written at their official site.
  • Bootstrap components can be integrated with other related components as it allows us to modify source code.

We should use bootstrap to build web page because of the above key reasons as well as it saves time and give a consistent look to our web page as compared to other web pages available on the internet. Through bootstrap one can design a web page as professional web pages designer without having too much knowledge about page design. A back-end developer can say himself as full stack developer with having knowledge of bootstrap because it’s allow him to develop complete web application (back-end as well as front-end) without the help of web page designer and as a  result a development cost is reduced. Also now bootstrap have large community support all around the world so whenever we face problems regarding bootstrap, we can easily find solutions.

Back to Top

How and where to get Bootstrap? And what does bootstrap package includes?

We can get Bootstrap from their official site which is http://getbootstrap.com/, from this site you will see the Download Bootstrap button, after clicking the button you will get another page which is actually download page contains three Download Bootstrap button which might be shown as below:Download Bootstrap

To use Bootstrap we just click the first Download Bootstrap button which contains compiled and minified CSS, JavaScript, and fonts but no document and source code files are included.

After clicking the first button we will get a zip file (package) which contains following files and their folder structure are shown below:Bootstrap Files

Under the bootstrap folder there are three folder css, js, and fonts. The css folder contains all the style sheets; js folder has two JavaScript files which contains all supporting scripts that are needed to include in a page when we use certain bootstrap components such as navigation bar, breadcrumbs etc. to work. The last fonts folder contains all the fonts from glyphicons are included.

Back to Top

What are responsive websites? Explain steps to create a simple webpage using bootstrap?

Responsive websites are those that maintain their look and feel and remain consistent across different display device with different pixel resolution. For example if we design a responsive web page for desktop PC which usually have large display device (as compared to mobile or tablet), then that page can be seen almost perfectly for all type of desktop monitors with different resolution; as well as this page maintains a consistent look of its component in other type of display devices such as mobile, tablet, smart TV etc. That responsive website adjust its layout base on screen size and pixel resolution.

Graphically represent this idea as:Responsive Design with Bootstrap

As seen from the above diagram the responsive web page maintains a consistence look across all type of devices, it also called mobile first approach.

Steps to create a simple web page using bootstrap are as follows:

Include the Content Delivery Network (CDN) provider link of bootstrap in web page; or get the bootstrap package from http://getbootstrap.com/ and then include main bootstrap.css or bootstrap.min.css  stylesheet file into the web page (html) though <link> element of html; then we can use various CSS classes of bootstrap; to build a simple responsive web page. But if we want to use specific css class such as navigation bar, breadcrumbs; then we also have to include the supporting JavaScript files link to the web page that come with the package or add related CDN link.

For example following is the simple html code (User information Input form) that build as a responsive web page using bootstrap:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Simple Responsive page for Large screen display</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
    <body>
        <div class="container-fluid">
            <h1>Simple Responsive page for large screen display</h1>
            <form>
                <div class="form-group">
                    <div class="col-lg-12">
                        <div class="row">
                            <div class="col-lg-3">
                               <label for="name" class="control-label">User Name</label>
                               <input id="name" type="text" class="form-control"/>
                            </div>
                            <div class="col-lg-3">
                                <label for="address" class="control-label">Address</label>
                                <input id="address" type="text" class="form-control"/>
                            </div>
                            <div class="col-lg-3">
                                <label for="nationalId" class="control-label">National ID</label>
                                <input id="nationalId" type="text" class="form-control"/>
                            </div>
                            <div class="col-lg-3">
                                <label for="income" class="control-label">Income</label>
                                <input id="income" type="text" class="form-control"/>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-3">
                                <button type="submit" class="btn btn-primary" style="margin-top: 5px;">Submit</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </body>
</html>

As seen from the code here, we use CDN link to include bootstrap.min.css file; then we use fluid layout container to build the form. As Bootstrap Grid System divide the page space into 12 equal columns; here we divide those 12 columns into 4 equal columns as a result each column contains space of 3 columns; also here we put first 12 column into a <div> element which contains bootstrap row class and we put each label and input element into a <div> element which contains bootstrap class col-lg-3. Actually through col-lg-3 class we divide page space and align the html content. Through this col-lg-* class we mainly represent this page for large display device having width pixel ≥992px.

We are going to discuss in detail about Bootstrap Grid System and Layouts in Bootstrap in next couple of questions, so don’t worry if you are not 100% clear about those concepts right now. You will get details about Grid System and Layouts with more practical examples later in this bootstrap interview questions series.

If we run this page in a PC monitor we will get the following view:

Responsive Design - Large Screen Display

We get view as we expected. But if we run this page in a small display device having width pixel less then 992px or reduce width of browser window we will get the following view:

Bootstrap Design - Large Screen Display

 

Here we see how bootstrap align our elements vertically to make the page responsive. Because of using the fluid container; each element of page always stress to edge of display device. To make the page stylish we use different CSS classes to different HTML elements. For example label have control-label class, input have form-control class and submit button have btn btn-primary class.

If we run this page into a more small display device or more reduce width of browser window we will get the following view:Bootstrap Design - Large Screen Display View

 

As we see this page still maintains its elements alignment in small display and we can interact with the page element without any hassle.  This is the main benefit of using bootstrap which help us to build responsive page.

Back to Top

What are the key components of Bootstrap? Explain with a diagram.

Key components of Bootstrap are:

  • HTML5 doctype.
  • CSS file contains media queries (support grid system).
  • Supporting JavaScript file (for building dynamic components).
  • Supporting fonts and glyphicons for making our pages stylish.

Below is the graphical representation of building block of Bootstrap:Major Bootstrap Components

As seen from the above diagram bootstrap use the HTML5 components to apply its CSS classes. As seen second layer of the diagram contains Containers (fixed or fluid) which is a special CSS class that house all other HTML components and it also help us to align component with help of other CSS class of bootstrap.

The Container contains divide whole page into 12 equal columns (with the help of CSS file that come with framework) where the each column can contains various component of HTML (Static or dynamic) as well as Glyphicons and images.

As seen from the diagram of (right-side) we can also divide a single grid into 12 equal columns, where each column can provide same functionality as left-side column; through this process we can build hierarchy of columns to our required level.  In order to build dynamic components of bootstrap, we must have to use the JavaScript file that is shipped with the framework; and there are also out-of-box Fonts and Glyphicons that helps us to make our web site more stylish.

Back to Top

What is Bootstrap Grid System? What are the different types of layouts available in Bootstrap? Please briefly explain each of them with example.

Grid system of bootstrap is the way in which it divide the available page space into equally 12 columns. We can even divide a single column into equal 12 column. That is how we create columns as many as we want but, we have to follow the rule number_of_columns X column_span=12. Graphically we can represent the idea as follow:Bootstrap Grid System

In Bootstrap there are mainly two types of layout:

  • Fixed-Layout, and
  • Fluid-layout.

Fixed-Layout in Bootstrap:

In bootstrap we implement fixed layout by using the .container class. Through this CSS, we can assign fixed number of pixels for HTML element with the help of its child CSS classes such .col-xs-*, .col-sm-*, .col-md-*, .col-lg-*, .col-xl-*. These classes are used to define column width of Bootstrap Grid System. Here (*) represent any number in between 1 to 12.

For example class .col-lg-12 represent 12 columns of grid with number of width pixel in between ≥992px and <1200px; although this layout system allows us to increase or decrease pixel number within certain range so the layout still show responsiveness at certain pixel number range; which is known as breakpoint that set by media query. That is fixed numbered pixel range specify the width of a column.

The main reason why we call as fixed-layout, because this container does not set its column pixel value in percentage and also placing its content from the middle of available width space and leave some extra space that look like margin of the page.

Fluid-Layout in Bootstrap:

We implement fluid layout by using .container-fluid class. Space allocation principle for a column is same as fixed layout but this container assign its column pixel value with percentage and use full available page space. Also media queries use percent value to calculate its breakpoint value and this layout stress its element to each edge of it view and leave no extra space that is use 100% of width space of display system.

For example consider the following which contains both fixed-layout as well as fluid-layout form:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Simple Responsive page for Large screen display</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
    <body>
        <div class="container">
            <h1>Fixed layout Form</h1>
            <form>
                <div class="form-group">
                    <div class="col-lg-12">
                        <div class="row">
                            <div class="col-lg-3">
                               <label for="name" class="control-label">User Name</label>
                               <input id="name" type="text" class="form-control"/>
                            </div>
                            <div class="col-lg-3">
                                <label for="address" class="control-label">Address</label>
                                <input id="address" type="text" class="form-control"/>
                            </div>
                            <div class="col-lg-3">
                                <label for="nationalId" class="control-label">National ID</label>
                                <input id="nationalId" type="text" class="form-control"/>
                            </div>
                            <div class="col-lg-3">
                                <label for="income" class="control-label">Income</label>
                                <input id="income" type="text" class="form-control"/>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-3">
                                <button type="submit" class="btn btn-primary" style="margin-top: 5px;">Submit</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <hr>
        <div class="container-fluid">
            <h1>Fluid layout Form</h1>
            <form>
                <div class="form-group">
                    <div class="col-lg-12">
                        <div class="row">
                            <div class="col-lg-3">
                                <label for="name" class="control-label">User Name</label>
                                <input id="name" type="text" class="form-control"/>
                            </div>
                            <div class="col-lg-3">
                                <label for="address" class="control-label">Address</label>
                                <input id="address" type="text" class="form-control"/>
                            </div>
                            <div class="col-lg-3">
                                <label for="nationalId" class="control-label">National ID</label>
                                <input id="nationalId" type="text" class="form-control"/>
                            </div>
                            <div class="col-lg-3">
                                <label for="income" class="control-label">Income</label>
                                <input id="income" type="text" class="form-control"/>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-lg-3">
                                <button type="submit" class="btn btn-primary" style="margin-top: 5px;">Submit</button>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
        </div>
    </body>
</html>

If we run this page into the browser which have large pixel resolution display monitor we will have the following view:Fixed Layout Vs Fluid Layout

As seen from the above screen the fixed layout’s container left certain amount of display space, of both edge of the screen. This layout does not utilized full (100%) of the display space. But in the case of fluid layout container full (100%) of display space is used to align its contents.

Now if we reduce the browser window width at certain amount to near about medium screen display then we have following screen display:

Medium screen display:Fixed and Fluid Layout in Bootstrap

As seen both layout resize it contents to make page responsive but still now fixed layout left some amount of space; both edge of the screen.

If we further reduce the browser window size near to small screen then will have the following Small screen display output:Fixed Layout Vs Fluid Layout in Bootstrap

In this case both layout utilized full space of the display device. So that the page still responsive.
Back to Top

What is container in Bootstrap? Kindly explain the concept with the help of examples.

In bootstrap container is a special class that allocate display device space and house all HTML elements and their supporting CSS classes to align HTML contents; and make page responsive. Through containers bootstrap implement its Grid Layout System. There are mainly two type of containers class in bootstrap .container class and .container-fluid class. The .container class allocate display space in fixed numbered pixel whereas .container-fluid class allocate display space in percentage (%). In container we mainly use two type of classes a) .row b) .col-*. Through row class we define a row and then we define column into the row; of bootstrap grid system, through .col-* class.

For example consider the following HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Simple Responsive page for Large screen display</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

</head>
<body>
<div class="container-fluid">
    <h1>Simple Responsive page for large screen display</h1>
    <form>
        <div class="form-group">
            <div class="col-lg-12">
                <div class="row">
                    <div class="col-lg-3">
                        <label for="name" class="control-label">User Name</label>
                        <input id="name" type="text" class="form-control"/>
                    </div>
                    <div class="col-lg-3">
                        <label for="address" class="control-label">Address</label>
                        <input id="address" type="text" class="form-control"/>
                    </div>
                    <div class="col-lg-3">
                        <label for="nationalId" class="control-label">National ID</label>
                        <input id="nationalId" type="text" class="form-control"/>
                    </div>
                    <div class="col-lg-3">
                        <label for="income" class="control-label">Income</label>
                        <input id="income" type="text" class="form-control"/>
                    </div>
                </div>
                <div class="row">
                    <div class="col-lg-3">
                        <button type="submit" class="btn btn-primary" style="margin-top: 5px">Submit</button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

</body>
</html>

If we run this code in browser we will find the following output:

Layout without Container in Bootstrap

From the output we see the .container-fluid class (container) utilized the full available space of the display device. Here we define two row with the help of .row class. In the first row we place four HTML input element along with label element. Each pair of element are define under a <div> element which contains col-lg-3 class as a result each pair of element of the first row occupy 25% space of the display device. In the second row we define only one element the submit button under .col-lg-3 class.

If we just change the container to .container of the above code then we will have the following output:Container in Bootstrap

As we seen from the output this container does not use full space of the display device also place its content from the center; arrow show the unused space of both edge. Another important think about this container is that, this container allow its child CSS to have fix numbered, in this each case col-lg-3 class will have fix numbered pixel space that determine by media query of the bootstrap.

Back to Top

Briefly explain Progress Bar in Bootstrap? How to create a basic progress Bar in Bootstrap? What contextual classes used with Progress Bar? Explain with example.

Progress bar in bootstrap is just more stylized HTML5 <progress> element. That is in bootstrap, we just use core HTML5 <progress> element with bootstrap’s special CSS classes; that specifically made for <progress> element.

To create a basic progress bar in bootstrap, we need two things, a <div> element and the <progress> element; with <div> element we define the caption text and show the progress percent; and behind the screen <progress> element do the actual work; we link up <div> element with <progress> element by the help of aria-described  attribute of <progress> element. That is <div> element’s id value and aria-described attribute’s value must be same.

For example the following code show how to create a basic progress bar in bootstrap:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Simple bootstrap progress bar</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css">
</head>
<body>
    <div class="container">
        <div id="linkId1" class="col-lg-12">Works in progress... 0%</div>
        <progress class="progress" value="0" max="100" aria-describedby="linkId"></progress>

        <div id="linkId2" class="col-lg-12">Works in progress... 45%</div>
        <progress class="progress" value="45" max="100" aria-describedby="linkId2"></progress>

        <div id="link3" class="col-lg-12">Works in progress... 80%</div>
        <progress class="progress" value="80" max="100" aria-describedby="link3"></progress>
    </div>
</body>
</html>

If we run this code in browser we will have the following output:Bootstrap Progress Bar

As seen from the output the value attribute of first progress bar is set to 0; so no progress is shown and we link the <div> and <progress> element through linkId1. Similarly we link second and third <div> and <progress> element through linkId2 and linkId3 respectively. Because of value attribute the second progress bar represent 45% progress graphically; similarly third progress bar represent 80% progress graphically.

The following contextual classes can be used with progress bar:  progress-success, progress-info, progress-warning, and progress-danger.

That is though contextual class we can apply some extra styling effect to the progress bar and it does not required extra <div> element.

For example consider the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Simple bootstrap progress bar</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css">
</head>
<body>
    <div class="container" style="margin-top: 5%">
        <h1>Contextual classes used with Progress Bar</h1>
        <br>
        <div class="col-lg-12">
            <progress class="progress progress-success" value="5" max="100"></progress>
        </div>
        <div class="col-lg-12">
            <progress class="progress progress-info" value="45" max="100"></progress>
        </div>
        <div class="col-lg-12">
            <progress class="progress progress-warning" value="85" max="100"></progress>
        </div>
        <div class="col-lg-12">
            <progress class="progress progress-danger" value="100" max="100"></progress>
        </div>
    </div>
</body>
</html>

If we run this code we will have the following output:Contextual Classes used in Progress Bar

As seen from the output those extra contextual classes are used to maintain consistent look with other bootstrap’s class style.

Back to Top

Explain the Responsive Utility Classes in Bootstrap? Give appropriate example with source code to demonstrate visibility on different devices screen size?

In bootstrap, Responsive utility classes are set of special classes whose sole purpose is to hide or display HTML elements base on screen resolution that determine by  media query of bootstrap. For example the .hidden-md-down hide an element if the screen resolution is extra small (<544px), small (≥544px – <768px) and medium (≥768px – <992px); and show only on large (≥992px – <1200px) and extra-large (≥1200px) display device.

For example consider the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of Bootstrap Responsive Utility Class </title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div class = "container-fluid" style = "padding: 5%">
        <h2>Bootstrap Responsive Utility Class </h2>
        <br>
        <div class = "col-xs-12 col-sm-3">
            <span class = "hidden-xs"><p class="bg-primary">Screen is not in extra small pixel range <544px)</p></span>
            <span class = "visible-xs"><p class="bg-info">Screen size is now in very small pixel range (&ge;544px - <768px)</p></span>
        </div>
        <div class = "col-xs-12 col-sm-3">
            <span class = "hidden-md"><p class="bg-info">Screen size is not in medium pixel range (&ge;768px - <992px)</p></span>
            <span class = "visible-md"><p class="bg-primary">Screen size is now in medium pixel range(&ge;768px - <992px)</p></span>
        </div>
        <div class = "col-xs-12 col-sm-3">
            <span class = "hidden-lg"><p class="bg-warning">Screen size is not in large pixel range(&ge;992px - <1200px)</p></span>
            <span class = "visible-lg"><p class="bg-info">Screen size is now in large pixel range(&ge;992px - <1200px) </p></span>
        </div>
        <div class = "col-xs-12 col-sm-3">
            <span class = "hidden-md-down"><p class="bg-danger">Screen size is now in between large and very large pixel range</p></span>
        </div>
    </div>
</body>
</html>

If we run this code in large screen display then we will have the following output:Bootstrap Responsive Utility Class - View1

As seen the at large screen display the first, second and third block show Screen size is not in * pixel range. Here (*) represent any screen size extra small, small and medium. Only last block show the current screen size pixel range; that is the current display device is either within large or very large pixel range. If reduce the browser width in certain amount that equal to medium range display device; then we will have following output:Bootstrap Responsive Utility Class - View2

As now the screen size in both range medium and very large pixel, but not in extra small and large pixel range. As seen, base on screen size bootstrap hide and show corresponding <span> elements. If we further reduce the screen size then we will have the following output:Bootstrap Responsive Utility Class - View3

As seen the extra-large block not showing at all and still the screen is not in any pixel range but out of extra-large pixel range display device. Now if we further reduce the screen size then we will have the following output:Bootstrap Responsive Utility Class - View4

As seen now the screen size fall into very small pixel range display, so visible-xs class work and corresponding <span> is shown. This is how the responsive utility classes are work in bootstrap based screen resolution.

Back to Top

How to create forms using Bootstrap? Briefly explain each form CSS class in bootstrap. Give an example of using each to generate forms.

In the context of bootstrap we create form through form-group class. We apply this class in a <div> and place that <div> element under the <form> element of HTML; and within that <div> element we place our desired other HTML elements to create form. Through bootstrap we can create vertical, horizontal, and inline form. By default every form are vertical because bootstrap apply display: block and width: 100% style to all HTML elements within a form by default.

The following code create a vertical form:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of vertical form</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
    <h1>Vertical Form</h1>
    <form>
        <div class="form-group">
            <label for="name">User Name</label>
            <input id="name" type="text" class="form-control"/>
        </div>
        <div class="form-group">
            <label for="address">Address</label>
            <input id="address" type="text" class="form-control"/>
        </div>
        <div class="form-group">
            <label for="nationalId">National ID</label>
            <input id="nationalId" type="text" class="form-control"/>
        </div>
        <div class="form-group">
            <label for="income">Income</label>
            <input id="income" type="text" class="form-control"/>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>
</div>
</body>
</html>

Here we put each pair of <label> and <input> element under the form-group class. If we run this code in browser we will have the following output:Bootstrap Vertical Form

As we seen the form-group class apply margin around it containing element and also help us to align elements vertically.

To create a horizontal form, first we have to include form-horizontal class to the <form> element; then we put pair of elements such as <label> and <input> under a <div> element that have CSS class form-group. To align elements horizontally; we also have to use the bootstrap grid system; that is, we have to specify the amount of space for each element under the <div class=”form-group”> element, so that they can align them self horizontally. For example consider the following code which represent horizontal form:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of Horizontal form</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
    <h1>Horizontal Form</h1>
    <form class="form-horizontal" >
        <div class="form-group">
            <label for="name" class="control-label col-sm-2">User Name</label>
            <div class="col-sm-10">
                <input id="name" type="text" class="form-control"/>
            </div>
        </div>

        <div class="form-group">
            <label for="address" class="control-label col-sm-2">Address</label>
            <div class="col-sm-10">
                <input id="address" type="text" class="form-control"/>
            </div>
        </div>
        <div class="form-group">
            <label for="nationalId" class="control-label col-sm-2">National ID</label>
            <div class="col-sm-10">
                <input id="nationalId" type="text" class="form-control"/>
            </div>
        </div>
        <div class="form-group">
            <label for="income" class="control-label col-sm-2">Income</label>
            <div class="col-sm-10">
                <input id="income" type="text" class="form-control"/>
            </div>
        </div>
        <div class="col-sm-offset-2 col-sm-10">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>
</div>
</body>
</html>

As seen from the code; for the first pair of elements we specify space for the <label> by using col-sm-2 class; and for <input> element we specify its space by using <div class=”col-sm-10“>; as a result in total we use 12 grid of bootstrap, to align element horizontally. Similarly we do the same thing for all other pair of elements except the last one; because here is only one <button> element and we do not use any <label> element; so we use col-sm-offset-2 class to make offset of 2 grid, so that the button align itself with the above <label> element; then we use col-sm-10 class to use utilized total 12 grid.

If we run the above code then we will have the following output:Bootstrap Horizontal Form

As seen all the form element align them self horizontally.

Finally the inline form; to create inline form we simply just have to use form-inline in <from> element and we will use the same code; that we used in making the vertical form as before. Inline form align its element side by side to form a single horizontal row. For example consider the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of Inline form</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container-fluid">
    <h1>Inline Form</h1>
    <form class="form-inline">
        <div class="form-group">
            <label for="name">User Name</label>
            <input id="name" type="text" class="form-control"/>
        </div>
        <div class="form-group">
            <label for="address">Address</label>
            <input id="address" type="text" class="form-control"/>
        </div>
        <div class="form-group">
            <label for="nationalId">National ID</label>
            <input id="nationalId" type="text" class="form-control"/>
        </div>
        <div class="form-group">
            <label for="income">Income</label>
            <input id="income" type="text" class="form-control"/>
        </div>
        <div class="form-group">
            <button type="submit" class="btn btn-primary">Submit</button>
        </div>
    </form>
</div>
</body>
</html>

As seen from the code all the thing are same as vertical form code; except here we only include form-inline class to <form> element. If we run this code we will have the following output:Bootstrap Inline Form

As seen; here all elements are place side by side to make a single row.

Back to Top

What are the different Bootstrap Components including Navbar, Breadcrum, Badges, Jumbotron etc.? Explain briefly each of them.

Bootstrap Navbar:

In bootstrap navbar is a special class that allow us to implement navigation system in web page. It along can do nothing; it work like an abstract class that allow other navigation related classes to implement specific type of navigation such as default navbar, inverse navbar, form navigation etc. The role of navbar is to change its content viewing process base on display device resolution. It may collapses all its content and then view those contents vertically if the display device width is small e.g. mobile device or view its content horizontally if the display device large enough. For example below code represent the default navigation bar.

Content of navbar.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example of Default Navigation Bar </title>

    <link rel="stylesheet" href="bootstrap.css">
    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>

</head>
<body>
    <div class="container">
        <div class="navbar navbar-default">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#defaultNavBar">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#">Default Navbar</a>
                </div>

                <div class="collapse navbar-collapse" id="defaultNavBar">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="#">Place holder 1</a></li>
                        <!-- drop down list -->
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">List place holder <b class="caret"></b></a>
                            <ul class="dropdown-menu">
                                <li><a href="#">List item1</a></li>
                                <li><a href="#">List item2</a></li>
                                <li><a href="#">List item3</a></li>
                                <li class="divider"></li>
                                <li><a href="#">List item4</a></li>
                                <li><a href="#">List item5</a></li>
                            </ul>
                        </li>
                        <li><a href="#">Place holder 2</a></li>
                        <li><a href="#">Place holder 3</a></li>
                        <li><a href="#">Place holder 4</a></li>
                    </ul>
                </div>
        </div>
    </div>
</body>
</html>

[Note: To run this code we must have to put navbar.html, bootstrap.css, jquery.js, bootstrap.js file in same folder.]

As seen from the code navbar serve as an abstract class through it, we implement default navigation bar with the help of navbar-dafault class. Here <div class=”navbar-header”> element contains <button> and <a> element. Then content of <a> element will be shown regardless of display size but the content of <button> will be shown when the display size is small. If the display size large enough then content of <div class=”collapse navbar-collapse” id=”defaultNavBar”> will also be shown. But when the display size is small then <button> element will be shown alongside with the <a> content, but in this case button represent link to the <div class=”collapse navbar-collapse” id=”defaultNavBar”> element’s content. If we run this code in browser then we will get the following output as:Bootstrap Navbar

As seen because of large screen all content are displayed except content of <button>. But if we reduce the browser size then we will have the following output:Navbar Vertical

As seen now <button> are shown and if we click the button then will have the following output:Navbar Small

As seen the <button> element now hold the link of <div class=”collapse navbar-collapse” id=”defaultNavBar”> element’s content. We implement this link through data-target=”#defaultNavBar” attribute of <button> with the id=”defaultNavBar” attribute of the place holder <div> element.

Bootstrap Breadcrum:

It use to represent current point of page navigation, as well as to represent site hierarchy. For example consider the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example of Breadcrumb</title>

    <link rel="stylesheet" type="text/css" href="bootstrap.css">
</head>
<body>
<div class="container">
    <ol class="breadcrumb">
        <li><a href="#">Page 1</a></li>
        <li><a href="#">Page 2</a></li>
        <li class="active">Page 3</li>
    </ol>
</div>
</body>
</html>

If we run this code then we will have the following output:Breadcrum in Bootstrap

As seen here class active represent current point of site navigation in this case the Page 3.

Bootstrap Badges:

It is another type of label but main difference between label and badge is; label represent in rectangular shape whereas badge represent in rounded shape. Badges are mainly used to represent numbers, notifications and so on. For example consider the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example of Badge</title>
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
</head>
<body>
<div class="container">
    <a href="#" class="btn btn-primary">number of notification <span class="badge">23</span></a>
</div>
</body>
</html>

If we run this code we will have the following output:Bootstrap Badges

As seen how class badge represent number 23 in rounded shape.

Bootstrap  Page Header:

It is a special class to represent page header. The main benefit of using this page header then normal HTML <h> page header is that through, it we can also place small subtitle alongside of big one. Also bootstrap allocate proper amount of space for it. For example consider the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example of Page header</title>
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
</head>
<body>
<div class="container">
    <div class="page-header">
        <h1>Big page header <small>small subtitle</small></h1>
    </div>
</div>
</body>
</html>

If we run this code then we will have the following output:Bootstrap Page Header

As seen how page-header class allocate proper space for <h1> and <small> element.

Bootstrap Alerts:

Bootstrap provide set of class which use to represent alert message. The class alert is an abstract class, so we have use it with other alert contextual class such as alert-success, alert-info, and alert-danger, alert-warning.  For example consider the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example of Alert Class</title>
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
</head>
<body>
<div class="container">
    <br>
    <div class="alert alert-success">Success alert message</div>
    <div class="alert alert-info">Info alert message</div>
    <div class="alert alert-danger">Danger alert message</div>
    <div class="alert alert-warning">Warning alert message</div>
</div>
</body>
</html>

If we run this code we will have the following output:Bootstrap  Alerts

As seen different alert message shown in different color.

Bootstrap  Jumbotron:

It is a special class that use to represent a big box with some information to catch user’s special attention to that information. For example consider the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Use of Jumborton</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div class="container">
    <div class="jumbotron">
        <h1>Use of Jumborton</h1>
        <p>Here we can represent other related information</p>
    </div>
</div>
</body>
</html>

If we run this code we will have the following output:Jumbotron in Bootstrap

As seen the Jumborton information is shown in big box to catch user attention.

Media Objects in Bootstrap:

It is a type of abstract class that use to build complex and iterative elements such as Facebook comments, blog comments and so on. Through it we can build hierarchy of components that either align left or right of their parent component. There are four type of media object default, nesting, alignment, and media list.

Bootstrap Panels:

It use represent contents such as text, image, link, table and so on, within a rounded corner box; that is, its act like a container. For example consider the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example of Panel use</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div class="container">
    <br>
    <div class="panel panel-default">
        <div class="panel-heading">
            Panel heading information
        </div>
        <div class="panel-body">
            Panel body can contains anything such text, image, table and so on.
        </div>
        <div class="panel-footer">
          <p>Give your desired footer contents</p>
        </div>
    </div>
</div>
</body>
</html>

Here we implement panel-default class. We can also use other available panel, such as .panel-primary, .panel-success, .panel-info, .panel-warning, or .panel-danger; to bring different rounded corner color box. If we run this code we will have the following output:Panels in Bootstrap

As seen through panel we can represent information with rounded corner box.

Bootstrap Well:

Though it we also represent information with rounded corner box but main difference between panel and well is that; the well does not have header and footer element like panel. We can make large and small well through related contextual well class such as: well well-lg, well well-sm.

Caraousel in Bootstrap:

In bootstrap through carousel class we implement sliding effect without using other third party JavaScript plugins and also required less coding to implement sliding effect as compared third party plugins.

Glyphicons:

In bootstrap glyphicons are used to represent small icons; although they look like image but glyphicons are lightweight font icons and not images. The main advantages of using glyphicons is; as they are font icons, their colors and sizes can be varied depending on display resolution.

Collapsing Elements:

In bootstrap the collapse plugin is also known as an accordion plugin. It is a plugin that contains multiple, vertically side by side tabs, but it can open only one tab at a time. The main advantages of using bootstrap collapsing elements is that; we do not have write single line of JavaScript code separately to implement collapsing; rather then we just we have to use html attribute and blocks of <div> element to implement collapsing.

Back to Top

More Bootstrap Interview Questions and Answers

How to create a dropdown menu in Bootstrap? Kindly give an example with complete source code?

In bootstrap we can create dropdown list with the help of  dropdown class. To create a dropdown list, first we include the dropdown class through a <div> element. Secondly, within this <div> element we include <a> and <ul> element. The <ul> element is hidden by default and the <a> element use to toggle the <ul> element; that is dropdown menu. The data-toggle attribute of <a> element tells Bootstrap to show the <ul> element with dropdown effect whenever <a> is clicked. On the other hand, the data-target attribute of <a> is used to prevent the page redirection. Here we define the actual resource link with in <ul> element and it should have the class dropdown-menu. Consider the following piece of code.

The content of dropdownlist.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Drop down List Example</title>
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>
</head>
<body>
<div class="container">
    <h1>Dropdown list example</h1>
    <div class="dropdown">
        <a data-toggle="dropdown" data-target="#">Dropdown <span class="caret"></span></a>
        <ul class="dropdown-menu">
            <li><a href="#">First link</a></li>
            <li><a href="#">Second link</a></li>
            <li><a href="#">Third link</a></li>
        </ul>
    </div>
</div>
</body>
</html>

[Note: Remember to put jquery.js, bootstrap.js, bootstrap.css and dropdownlist.html in the same folder].

If we run this code we will have the following output as:Dropdown List Bootstrap

As seen the <ul> element is hidden. If we click on the Dropdown then the <ul> element will be shown as:Bootstrap Drop down List

As seen all the <ul> element shown and if we click somewhere else on the page; then the <ul> element will again be hidden; that is how it represent the toggle behavior.

Back to Top

What is a bootstrap list group? And why to use it? Kindly explain its use with the help of an example.

Bootstrap list group is nothing but a CSS class that applied to <ul> element. Through list-group class we apply style of bootstrap to the <ul> element; it’s also help us to align elements within <ul> as well as help us to integrate and maintain consistence look with other elements of bootstrap.  To create list group, we also need to apply list-group-item class to the <li> elements. The <li> element contains the actual content of list group. For example consider the following code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example of list group</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
    <div class="container">
        <br>
        <ul class="list-group">
            <li class="list-group-item">read mail number <span class="badge">14</span></li>
            <li class="list-group-item">unread mail number <span class="badge">4</span></li>
            <li class="list-group-item">todo list <span class="badge">7</span></li>
        </ul>
    </div>
</body>
</html>

As seen from the above code how we integrate badge class into <li> element. If we run this code we will have the following output:Bootstrap List Group

As seen from above how list-group class together with the list-group-item class help us to align <li> element as well as integrate other classes, as in this case we integrate badge class.
Back to Top

How to create a menu using navbar-inverse in Bootstrap?

In bootstrap navbar is a special class that allow us to implement navigation system in web page. It alone can do nothing; it work like an abstract class that allow other navigation related classes to implement specific type of navigation such as default navbar, navbar-inverse. The role of navbar is to change its content viewing process base on display device. It may collapses all it content and then view those content vertically if the display device width is small e.g. mobile device or view its content horizontally if the display device large enough. For example below code represent the inverse navigation bar.

Content of inversenavbar.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example of Inverse Navigation Bar</title>
    <link rel="stylesheet" href="bootstrap.css">
    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>
</head>
<body>
    <div class="container">
        <div class="navbar navbar-inverse">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#inverseNavBar">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" href="#">Default Navbar</a>
                </div>
                <div class="collapse navbar-collapse" id="inverseNavBar">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="#">Place holder 1</a></li>
                        <!-- drop down list -->
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown">List place holder <b class="caret"></b></a>
                            <ul class="dropdown-menu">
                                <li><a href="#">List item1</a></li>
                                <li><a href="#">List item2</a></li>
                                <li><a href="#">List item3</a></li>
                                <li class="divider"></li>
                                <li><a href="#">List item4</a></li>
                                <li><a href="#">List item5</a></li>
                            </ul>
                        </li>
                        <li><a href="#">Place holder 2</a></li>
                        <li><a href="#">Place holder 3</a></li>
                        <li><a href="#">Place holder 4</a></li>
                    </ul>
                </div>
        </div>
    </div>
</body>
</html>

[Note: To run this code we must have to put inversenavbar.html, bootstrap.css, jquery.js, bootstrap.js file in same folder.]

As seen from the code navbar serve as an abstract class through it we implement inverse navigation bar with the help of navbar-inverse class. Here <div class=”navbar-header”> element contains <button> and <a> element. Then content of <a> element will be shown regardless of display size but the content of <button> will be shown when the display size is small. If the display size large enough; then content of <div class=”collapse navbar-collapse” id=”inverseNavBar”> will also be shown. But when the display size is small then <button> element will be shown alongside with the <a> content, but in this case button represent link to the <div class=”collapse navbar-collapse” id=”inverseNavBar”> element content. If we run this code in browser then we will get the following output as:Inverse Bar in Bootstrap

As seen because of large screen all content are displayed except content of <button>. But if we reduce the browser size then we will have the following output:Bootstrap Inverse Bar

As seen now <button> are shown and if we click the button then will have the following output:Inverse Bar

As seen the <button> element now hold the link of <div class=”collapse navbar-collapse” id=”inverseNavBar”> content. We implement this link through data-target=”#inverseNavBar” attribute of <button> with the id=”inverseNavBar” attribute of the place holder <div> element.
Back to Top

How to make an image responsive in Bootstrap? Kindly explain with code sample?

In bootstrap we make image responsive through .img-responsive class that applied to <img> element of HTML. The main advantage of using responsive image over non-responsive is that responsive maintain its height and width with the parent element that hold the image or with the display device size. Consider the following code of responsive image.

Content of responsiveImage.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of Responsive Images</title>
    <link rel="stylesheet" href="bootstrap.css">
    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>
</head>
<body>
<div class="container">
    <h2>Non-Responsive Image</h2>
    <div>
        <img src="someImage.png" alt="Non Responsive Image">
    </div>
    <hr>
    <h2>Responsive Image</h2>
    <div>
        <img src="someImage.png" class="img-responsive" alt="Responsive Image">
    </div>
</div>
</body>
</html>

[Note: run this code we must put responsiveImage.html, bootstrap.css, jquery.js, bootstrap.js and someImage.png file in same folder].

If we run this we will have the following output:Responsive Image

In normal screen size, we can see both image without any image size distortion. Now if we reduce the browser size at certain level then we will have the following output as:Responsive Image in Bootstrap

As seen above, the non-responsive image is not resized itself, on the other hand, the Responsive image resized itself. If we further reduce the browser size then we will have the following output:Bootstrap Responsive Image

We can see now, non-responsive image is not fully visible but we still can see responsive image fully; because the responsive image always tries to maintains its size with respect to display screen size (in this case the browser).
Back to Top

Kindly explain the following bootstrap plugins? Modal, Scrollspy, Affix, Transition?

Modal: In bootstrap we can create modal dialog window with the help of modal class. Almost all modal windows has three part including header, body and footer; and by default all modal windows are hidden in web page until we specify a certain condition on which a specific modal window appear. We can implement all of those stuff by using bootstrap class as follow.

Content of modalwindow.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example of Modal Window</title>
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>
</head>
<body>
<div class="container">
    <br>
    <h1>Example of Modal Window</h1>
    <div class="modal fade" id="linkToModalWindow">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Put modal header title here</h4>
                </div>
                <div class="modal-body">
                    <p class="bg-primary">Put required information to the modal body</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary">Apply Change</button>
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
    <p class="bg-info">Click the Button to launch the modal window</p>
    <button class="btn btn-primary" data-toggle="modal" data-target="#linkToModalWindow">
        Launch Modal Window
    </button>
</div>
</body>
</html>

[Note: To run this code we must put modalwindow.html, bootstrap.min.css, jquery.js, bootstrap.js file in same folder]

Here we first implement the modal class and to apply fading effect we also include the fade class; we set modal window id as id=”linkToModalWindow”; this first <div> element act as modal window container; since modal window is one type of dialog box so second <div> contains the class “modal-dialog”; Now within modal-dialoag <div> element we define modal-content <div> into which we define rest of modal window content such header, body and footer with help of modal-header, modal-body and modal-footer respectively; and to trigger the modal window, we define a button below the page and set its data-toggle attribute to modal and set data-target attribute to linkToModalWindow; to identify our desired modal window. So when we click the button the modal window get appear with fading effect as shown below:Bootstrap Modal

We can cancel the modal window either by clicking the X or Close button or by clicking anywhere else outside the modal window. Here Apply Change is a dummy button; have no action at all.

Scrollspy: It is a type of navigation system of web page that link page content to a page menu. That is, when we click certain menu item then the page automatically scroll down to the beginning of that specific page content. For example consider the following code.

Content of scrollspy.html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example of Scrollspy</title>
    <link rel="stylesheet" type="text/css" href="bootstrap.css">
    <script src="jquery.js"></script>
    <script src="bootstrap.js"></script>
</head>
<body>
<div class="container">
    <!--navigation bar-->
    <nav id="scrollSpyExample" class="navbar navbar-default" role="navigation">
        <div class="container-fluid">
            <div class="navbar-header">
                <button class="navbar-toggle" type="button" data-toggle="collapse" data-target=".navbarLinks">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="#">ScrollSpy navigation</a>
            </div>
            <div class="collapse navbar-collapse navbarLinks">
                <ul class="nav navbar-nav">
                    <li class="active"><a href="#home">Home</a></li>
                    <li><a href="#service">Service</a></li>
                    <li><a href="#product">Product</a></li>
                    <li><a href="#contuctUs">Contact Us</a></li>
                </ul>
            </div>
        </div>
    </nav>

    <!--page content-->
    <div data-spy="scroll" data-target="#scrollSpyExample">
        <h3 id="Home">Home</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

        <h3 id="service">Service</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

        <h3 id="product">Product</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>

        <h3 id="contuctUs">Contact Us</h3>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
</div>
</body>
</html>

[Note: To run this code we must put scrollspy.html, bootstrap.min.css, jquery.js, bootstrap.js file in same folder]

Here we first implement the navbar-default and set its id attribute value to scrollSpyExample. Next we define the <div> element that hold the page content with data-spy attribute to scroll and data-target attribute to scrollSpyExample. With the data-target attribute we linkup the default navigation bar with <div> element that have page content. Here we include some dummy content to test scroll spy navigation system.  If we run the page in browser; and then reduce the vertical length of the browser window; then if we click any of the navigation link “Home”, “Service”, “Product”, and “Contact Us” then we will see that page automatically scroll down to that specific content as shown below:ScrollSpyIf we click on the Service of the navigation bar then the page will scroll down to service content as:Bootstrap ScrollSpy

We make up this link through href attribute of <a> element from navigation bar to the id attribute of every <h3> elements those under the <div data-spy=”scroll” data-target=”#scrollSpyExample”> element.

Affix: Through affix we can fix a component position to a specific place of web page; that is the component will be fixed at that point all the time even scroll up or down the web page. This is usually used in navigation menus or social icon buttons, to make icon fixed at a specific area while scrolling up and down the page. For example consider the following code.

Content of affix.html file.

<!DOCTYPE html>
<html>
<head>
  <title>Affix Example</title>
  <link rel="stylesheet" href="bootstrap.min.css">
  <!--include the link of jquery-->
  <script src="jquery-3.1.1.min.js"></script>
  <script src="bootstrap.min.js"></script>
</head>
<body>

<div class="container jumbotron">
  <h1>Here we Jumbotron like as header component</h1>
  <p>This is Example of Using affix</p>
  <p>Here affix applied in navigation bar.</p>
</div>

<!--add some custom style sheet to navbar-->
<nav class="navbar navbar-default" data-spy="affix" style="top: 0px; width: 100%">
  <ul class="nav navbar-nav">
    <li class="active"><a href="#">Affix navigation</a></li>
    <li><a href="#">Home Page link</a></li>
    <li><a href="#">Service Page link</a></li>
    <li><a href="#">Product Page link</a></li>
  </ul>
</nav>

<div class="container">
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
  <h2>Plese input some text here </h2>
</div>

</body>
</html>

[Note: To run this code we must put affix.html, bootstrap.min.css, jquery-3.1.1.min.js, bootstrap.min.js file in same folder]

As seen from the code here we apply affix to the default navigation bar through the data-spy attribute; here we also apply style so that the affix stick at top and use full width of the display device. If we run this code we will have the following output as:Affix

As seen the navigation bar is place at the top of the page. Now if we scroll down to see the page content below then we will have the following output:Affix in Bootstrap

As seen because of affix the navigation bar is fixed at the top; even other contents of the page move as we scroll down. If we further scroll down the page then then we will have the following output:Bootstrap Affix

As seen the navigation bar still fixed at top.

Transition: This is just a bootstrap plugins that allow us to apply transition or fading effect to the other components of web page. For example because of this plugins the modal box, tab, alert, carousel panes show some short of transition or fading effect.
Back to Top

Bootstrap is the world’s most popular mobile ready web development framework for HTML, CSS and JavaScript. Bootstrap is for you if you want to quickly build a super cool website which work across devices and browsers. It is easy to learn and super powerful.

Following are the section details of this online course:

  • Section 1: Getting Started With Bootstrap
  • Section 2: Photo App Sales Website
  • Section 3: Portfolio Resume Using SASS
  • Section 4: Social Network Template
  • Section 5: Agency Landing Page Using LESS
  • Section 6: Photo Gallery
  • Section 7: CMS Admin Template
  • Section 8: Web Hosting Company Website
  • Section 9: Ecommerce Template
  • Section 10: Business Bootstrap Theme
  • Section 11: Blog Website
  • Section 12: Course Summary

Learn Bootstrap by Example

Advanced Web Developer Interview Questions Series:

The post Top 15 Bootstrap Interview Questions – MUST HAVE appeared first on Web Development Tutorial.

MUST Have C# Interview Questions and Answers – Part 2

0
0

This C# Tutorial Part-2 in series of C# Interview Questions with practical and detailed answers. In previous part, we covered many basic to intermediate level interview questions on C# with the help of practical examples. I’ll recommend strongly to go through part-1 in this series. We will continue this series to provide more practical details with real time scenarios and complete source code to grasp C# language concepts. But this time, we are understanding in a different way by comparing different concepts.C# Interview Questions and Answers

C# Interview Questions PDF version will be available later for download.


Following Technical Interview Questions and Answers will also be helpful.


Start Date: Aril 01, 2017 12:00 AM PST
End Date: May 01, 2017  6:00 AM PST

Udemy Courses Online

Take All Online Courses – Lifetime Access

Complete C# Interview Questions List

Managed Vs Unmanaged Code

Managed Code:

The code (like Vb.Net,C#,J#) which is written in .Net Framework and developed by .Net Framework and under the control of CLR(Common Language Runtime). And the garbage collector run automatically in managed code.

Unmanaged Code:

The code which is developed outside of the .Net framework is called unmanaged code. Unmanaged code does not run under the control of CLR. Unmanaged code executed with help of wrapper class CCW (COM Callable Wrapper) and RCW(Runtime Callable Wrapper). C++ can be used to write such application.

Back to top

Struct Vs class

Structs and classes are the template or blue print that is used to create an object of a class.

Class Struct
Classes can be inherited Structs are not inherited
Classes are reference type Structs are value type
It could be null It could not be null
Class can be abstract It cannot be abstract
You can override the method within class You cannot override the method within Struct
  • A struct always contain public default parameter less constructor it can not contain the private parameter less constructor.
    struct A
    {
       private A()  // compile time error
           {    }
    }
    
    
    class B
    {
       private B()  // run successfully
    }
  • Static constructor is triggered in case of class but not in case of structure.
    struct A
    {
        static A() 
        {
            Console.WriteLine("This is Constructor A()");
        }
    }
    
    
    class B
    {
        static B()
        {
           Console.WriteLine("This is Constructor B()");
        }
    }
    
    class Program
    {
       static void Main(string[] args)
       {
          //Nothing happen
          A a =new A();                    
         
          //Will out put This is me a class
          B  b=new B();                           
    
          Console.Read();
       }
    }
    Output: This is Constructor B()

Back to top

Abstract Vs Interface

Abstract class and interface both are used to achieve abstraction (for hiding the functionality). Both contain the abstract method.

Abstract Class Interface
Abstract class contain both abstract and non-abstract method Interface contain only abstract method
It contain final, non-final,static,non-static variable It contain only static and final variable
Abstract class provides the implementation of interface It cannot provide implementation of abstract class
It does not support multiple inheritance Interface supports multiple inheritance
Abstract keyword is used to declare abstract class Interface keyword is used to declare the interface

Example of an Abstract class:

namespace ConsoleApplication
{
   abstract class A                  // contain method body
   {
      public int add(int a,int b)   
      {
          return a+b;
      }
   }

   class B : A       //classs B extends class A
   {
     public int mul(int a,int b)
      {
         return a*b;
      }
   }

   class TestMain
   {
      Static void Main(string[] args)
      {
         B ob=new B();
         int result=ob.add(5,10);
         Console.WriteLine(“result {0}”,result);
         Console.ReadLine();
      } 
   }
}

Example of Interface:

namespace ConsoleApplication
{
   interface A          // can not contain method body
   {
      void method();    //public abstract by default
   }

   class B : A          // class B implements interface A
   {
      Void mehtod()
      {
            Console.WriteLine(“Hello Welcome”);
            Console.ReadLine();
      }

      Static void main(string[] args)
      {
         B ob=new B();
         ob.mehod();
      }
    }    
}
Back to top

Boxing Vs Unboxing

In C# there is three types of data type Value type,Reference Type and pointer type. The process of the converting a value type into reference type is called Boxing. While the Reference type is converting into value type called unboxing.

Int a=5;
Object obj=5;    //Boxing
Int a=(Int)obj;    //Unboxing

Example of Boxing and Unboxing:

namespace ConsoleApplication1
{
      internal class Program
      {
         private static void Main(string[] args)
         {
             double a;
             object ref;
             a = 100;

             ref = a;            //Boxing - Value type to Object
             double result = (double)ref;   // UnBoxing - Reference Type to Value
             Console.WriteLine(Result);   // 100
             Console.ReadLine();  
         }
      }
}

Back to top

Method Overloading Vs Method Overriding

Method Overloading Method Overriding
Method Overloading is used for increasing the code readability Method Overriding is used for code re-usability
Parameter must be different Parameter must be same
It can perform within the class It occurs in two classes using inheritance (parent and child class)
It perform compile time polymorphism It perform runtime polymorphism
No special keyword to use for method overloading. It can perform simply within the class. Using virtual keyword with the base class method and override keyword with derived class method can achieved method overriding.

Example of Method Overloading:

namespace ConsoleApplication
{
    class Calculation
    {
        public void add(int a,int b)
        {
           Console.WriteLine(a+b);
        }
        public void add(int a,int b,int c)
        {
          Console.WriteLine(a+b+c);
        }
    }
    class TestMain
    {
       static void Main(string[] args)
       {
             Calculation ob=new Calculation();
             ob.add(5,10);
             ob.add(5,10,15);
       }
    }
}

Example of Method Overriding:

namespace ConsoleApplication
{
    class A
    {
        public virtual void Method()                                // Virtual method
        {
            Console.WriteLine("This is the Base Class");
        }
    }

    class B : A
    {
        public override void Method()                                // Overriding virtual method 
        {
            Console.WriteLine("This is the Derived Class");
        }
    }

    class TestMain
    {
        static void Main()
        {
           B ob=new B();
           ob.Method();//                   output:  This is Derived Class
        }
    }
}
Back to top

Break and Continue Statements

Break statement is used to break out of loop that’s mean you can jump out of loop at the current position and it terminate the loop.

Continue statement is used to (one iteration) jump over one iteration and again it continues the loop.

namespace ConsoleApplication
{
    class A
    {
        static void Main(string[] args)
        {
 
          int i;          
          for (i = 0; i <= 10; i++)
          { 
              if (i == 4)                // it jump out of loop where i==4  and start again from next value      
                  continue;
             
              if (i == 7)              // iteration stoped when i==7 and terminate the program
                  break; 
              Console.WriteLine(i);            
          } 
          Console.ReadLine();              
        }    
    }
}

Output:
0
1
2
3
5
6

Back to top

Constant Vs Read-Only

Constant and Read-only is the keyword that is used to make the field constant that can not be modified.

Constant Value:

Constant variable or local variable are assigned at the time of declaration they cannot be modified after the declaration. Constant variables are static by default hence you cannot use static keyword with the constant field (or variable).

public const int a=1;

ReadOnly:

A read-only field can be assigned either at the time of declaration or inside the constructor of the same class, that’s why read only field can be used run-time constant.

class A
{
  readonlyint a=1;
  readonlyint b

  public A(int a)
  {
    this.a=a;
  }
}

Back to top

Ref and out parameters

Ref and out parameters are used to pass an argument into a method. By using this parameter you can return more than one value.

In the case of ref parameter first you need to initialize it then pass to the method but for out parameter, you don’t need to initialize.

Ref:

The ref keyword is used to pass an argument as a reference. When the value of that parameter will be changed in the method, it will be reflected in the calling method.

It needs to be initialized before passing into the method.

class A()
{
    Static void Main()
    {
       Int a;     //need to be initialised
       a=1;

       method(ref a)
       Console.Write(a);
    }

    public static void method(ref int b)
    {
        B+=5;
    }
}

Output: 6

Out:

The out keyword is used to pass an argument same as ref keyword but in the case of out ref, you can pass the argument without assigning the value. Instead, it must be initialized in the called method before it returns back to the calling method.

class A
{
    Static void Main()
    {
        Int a,b;         // no need to be initialised
        Method(out a, out b)
        Console.Write(a);
        Console.Write(b);
    }

    Public static intmethod(out int n, out int m)
    {
       n=2;
       m=5;
       return 0;
    }
}  

Output:
2
5

Back to top

String Vs String Builder

String:

String is Reference type data type, you cannot insert, modify or delete any data when a string is created that means in simple word we can say that string is an immutable means once you created the object of string you cannot modify it when you try to modify it will create a new object in memory.

String s1= “Hello Jackson”;
String s1=”Hye Jackson”;      // created a new object

String Builder:

String Builder is an object of string to work with string we have to use a namespace(“Using System. Text) so unlike string, a string builder is an object and we can apply insert, modify and remove function in string builder without creating a new object, It will automatically update in memory does not create new space in memory. We can also say that string builder is mutable that’s mean changeable.

StringBuildersb=new StringBuilder();
sb.append(“Hello jackson”);
sb.replace(“hiijackson”);     //updating string memory

Back to top

Array.copyTo() Vs Array.Clone()

Array.copyTo () and Array. Clone() both areused to replicate the element of existing Single dimension array.

Array.copyTo:

Array.copyTo () method copy the array’s element into existing/destination array with the reference of targeted instance of existing/destination array. You can say that Array.copyTo allows to replicate the into specified index.

Array.Clone():

Array. Clone () replicate the existing element array in the new array object containing all element of exiting array without having any reference.

using system;

class copycloneexp
{
   public static void Main()
   {

      Int[] existingarray=new int[3];
      existingarray[0]=10;
      existingarray[1]=15;
      existingarray[2]=20;

      Int[] destinationarray = new int[existingarray.Length]
      existingarray.CopyTo(destinationarray,0); 
      
      int[] destinationarray1;
      destinatioarray1=existingarray.CloneTo() as int; // exp of array.cloneto()
   }
}

Back to top

Dispose and Finalise methods

Memory management is a big challenge when you are developing a web Application/software as we know that Garbage Collector plays the main role in .Net to manage unmanaged resource and Dispose and finalize method both are part of Garbage Collector.

Dispose and finalize method both are used to reclaim the memory used by the unmanaged resource.

Dispose method Finalize method
Unlike Finalize method it is not directly called by GC, User has to write code to implement it. Finalized method is automatically called by GC when any resource goes out of scope or at end of program.
It is a faster method and called by the user for instant object disposal. It is a slower method and automatically called by GC at end of,User can only override method when indeed.
Dispose method is the part IDisposable interface in GC Finalize method is the part of object class in GC
using System;
using System.Diagnostics;

public class A
{
   Stopwatch watch;

   public A()
   {
      watch = Stopwatch.StartNew();
      Console.WriteLine("Instantiated object");              // Instantiated object 
   } 

   public void ShowDuration()
   {
      Console.WriteLine("This instance of {0} has been in existence for {1}",this, sw.Elapsed);
   }

   ~A()
   {
      Console.WriteLine("Finalizing object");                 // Finalizing object
      sw.Stop();
      Console.WriteLine("This instance of {0} has been in existence for {1}",
                        this, sw.Elapsed);
   }
}

public class Demo
{
   public static void Main()
   {
      AClass ob = new AClass();
      ob.ShowDuration();
   }
}
Back to top

Late binding Vs Early binding

If the methods have same name and different parameter declare in a single class or methods have same name and same parameter but declare in different classes then it is called Binding or Polymorphism.

Late Binding:

It is also called runtime polymorphism; the situation arrives when methods are virtual and have same name and same parameter in different classes (must be derived class). Then it is called method overriding or late binding.

using System;  

public class Vehicle
{  
    public virtual void run()
    {  
        Console.WriteLine("Running...");  
    }  
}  

public class Bike: Vehicle  
{  
    public override void run()  
    {  
        Console.WriteLine("Bike is running safely...");  
    }      
}  

public class TestMain  
{  
    public static void Main()  
    {  
        Vehicle a= new Bike();       // object  id determined at runtime
        a.eat();  
    }  
}   


Output: Bike is running safely

Late Binding:

It is also called compile time polymorphism; the situation arrived when methods have same name but different parameter in same class.

It is also called method overloading.

using System;

public class A
{
  public void Sum(int a, int b)
  {
       Console.WriteLine(a + b);
  }

  public void Sum(int a, int b, int c)
  {
       Console.WriteLine(a + b + c);
  }
 
  static void Main(string[] args)
  {
     A ob=new A();                       // Object is determined at compile time 
     ob.Sum(5,8);
     ob.Sum(5,8,10);
  }
}

Back to top

IEnumerable & IQueryable

IEnumerable and IQueryable are used for data manipulation in LINQ from the database and collection.

IEnumerable IQueryable
It exists in System. Collections Namespace It exists in System.Linq Namespace
It is the best for query data from in memory collections like List, Array etc. It is best for query data from out-memory (like remote database, Service) collection.
It execute select query on server side, load data in memory on client side and then filter data. It executes select query on server side as well as filtered there.
Suitable for LINQ or Object and LINQ to XML queries Suitable for LINQ to SQL queries
It does not supports the custom query It supports custom query using Create Query and Execute method
It supports lazy loading that’s why suitable for paging It does not support lazy loading that’s why not suitable for paging
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Collections;
 
namespace TesIEnumerable
{
    class A
    {
        public static void Main(String[] args)
        {
            IEnumerable<int> data = from value in Enumerable.Range(1, 10) select value;
            foreach (int a in data)
            {
                Console.WriteLine(a);
            }
            
            Console.ReadLine();
        }
    }
}


Output:
1
2
3
4
5
6
7
8
9
10
Back to top

Throw Exception Vs Throw Clause

Throw Exception Throws Clause
It is used to throw an exception explicitly It is used to declare an exception
It is used inside the method body to invoke an exception. It is used in method declaration(signature)
You cannot throw more than one exception You can throw multiple exceptions
Follow by instance variable Follow by exception class name

Throw Exception Example:

static
{
    try
    {
       throw new Exception(“Logical Error”);
    }
    catch(Exception ex)
    {
       console.WriteLine(“Error:” + ex.geMessage())
    }
}

Throws Clause Example:

public void method() throws ArithmeticExeption
{
  ArithmeticExeption ex = new ArithmeticException();
  throw ex;
}
Back to top

== Vs equals

The == operator compare the reference of the object while the equals compares the contents of the object see the bellow example.

namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {

           Object o1 = "Sachin";
           char[] c={'S','a','c','h','i','n'};
           
           Object o2 = newString(c);
           Console.WriteLine(o1==o2);            //compare the reference
           Console.WriteLine(o1.Equals(o2));     // compare the contents
          
           Console.ReadKey();

        }
    }
}

Output:
False
True

Back to top

Is Vs as operator

Is operator is used to checking the Object type and it returns the Boolean value true if the object is same otherwise returns false.

The as operator perform the conversions between compatible types.it is also work similar as Is operator but instead of return Boolean value it returns the object if they are compatible type otherwise returns null.

Example of Is Operator:

class A 
{}

class B : A
{}

public class IsOperator
{
    static void Main()
    {    
        A a = new A();
        B b = new B();

        Console.WriteLine(a is A);
        Console.WriteLine(a is Object);
        Console.WriteLine(b is A);
        Console.WriteLine(a B);
    }
}

Output:
True
True
True
False

Example of as Operator:

using System;

class A {}
class B : A {}

public class AsOperator
{
    static void Main()
    {    
        object[] objects = new object[6];
        objects[0] = new A();
        objects[1] = new B();
        objects[2] = "Hello";
        objects[3] = 12;
        objects[4] = 1.4;
        objects[5] = null;

        for (int i=0; i<objects.Length; ++i) 
        {
            string str = objects[i] as string;
            Console.Write ("{0}:", i);

            if (str != null)
                Console.WriteLine (str);
            else
                Console.WriteLine ("not a string");
        }
    }
}


Output:
0: not a string
1: not a string
2: Hello
3: not a string
4: not a string
5: not a string
Back to top

Array Vs Array List

Array Array List
Array is collection of similar data types that’s mean we can store only one data type either Int,string,char….etc. Array List is the collection of different data types that’s mean we can store all data types in array list.
The length of array is fixed Array list can decrease or increase dynamically as per usage
Array belongs to System. Array namespace It belongs to System. Collection namespace

Array Example:

namespace Example1
{
    class ArrayExample
    {
        static void display(int[] array)
        {
            Console.WriteLine("Elements of array are:");
            foreach (int i in array)
            {
                Console.Write("\t{0}", i);
            }
        }

        static void Main(string[] args)
        {
            int[] arr = new int{25,15,5,10};
            int i;
            // loop for accepting values in array
            for (i = 0; i < 4; i++)
            {
                arr[i] = Convert.ToInt32(Console.ReadLine());
            }
            ArrayExample.display(array);
            //sorting array value;
            Array.Sort(array); //use array's sort function
 
            ArrayExample.display(array);
            Console.ReadLine();
        }

    }
}

Output: Elements of array are:
5  10  15  25

ArrayList Example:

using System;
using System.Collections;

class Program
{
    static void Main()
     {
        ArrayList list = new ArrayList(); // Create an ArrayList with four strings.
        list.Add("USA");
        list.Add("London");
        list.Add("Brazil");
        list.Add("India");
       
        list.Sort();  // Sort the ArrayList.
        foreach (string value in list)
        {
            Console.WriteLine(value);
        }
        
        list.Reverse();    // Reverse the ArrayList.
        foreach (string value in list)
        { 
           Console.WriteLine(“Reverse  Arraylist…………..”)
            Console.WriteLine(value);
        }
    }
}

Output:
Brazil
India
London
USA
Reverse  Arraylist…………..
USA
London
India
Brazil
Back to top

Directcast Vs ctype

Directcast cType
Directcast is generally used to cast reference data type. It is used to cast value type.
To perform the Directcast between two different classes, the classes should have relationship between them. To perform ctype b/w two different value types, relationship is not required. If the conversion is legal it will be performed.
When you perform Directcast on arguments that do not match it will throw InvalidCastException. Exception is not thrown while perform ctype.
Performance of Directcast is better than ctype because there is no runtime helper routines of VB.Net are used for casting. It requires runtime helper routine of VB.Net hence performance is slow that Directcast.
Directcast is portable across many language that’s mean it is not specific to VB.Net Ctype is not portable it is specific to VB.Net.

Directcast Example:

Object exp = ”public keyword is access modifier”;
String exp1 =(string) exp;
Object exp2 = exp1;
Object exp3 = (object) exp1;

Type Cast Example:

TextBox exptype=(TextBox)obj;
Where obj is  Typecast

Back to top

Public Vs Static Vs void

Public: public keyword is access modifier and tells the c# compiler that the Main method is accessible by anyone.

Static: static keyword declared that the Main method is global and can call without creating an instance of the class.

Void: void keyword is used to specify that the Main method does not return any value.

Example of public and static keyword:

using System;

namespace staticexample
{
    class A
    {
        public static int a;             // static variable can be initialised out side of member function
        public static void display()     // static and void method means no return type
        {
            a=10;
            Console.WriteLine(a);
        }
        public void demo()            //  public and void method means non return type
        {
            int b=20;
            Console.WriteLine(b);
        }

 
        static void Main(string[] args)
        {
            A obj = new A();
            A.display();              //calling display method through class name
            obj.demo();               //calling demo method using instance of class
            Console.Read();
        }
    }
}

Output: 10
        20
Back to top

Top Technical Interview Questions and Answers Series:

Top C#.NET Jobs [Updated Daily]

Top ASP.NET MVC Jobs

ASP.NET Developer, 100% remote
Source: Indeed
Details: Core development tools are C#, ASP.NET 4 & 4.5, ASP.NET MVC 5, Web-form knowledgeable, NUnit, CSS, HTML, Entity Framework 6, SQL Store Procedures, jQuery, SQL...  More
30+ days ago

Remote 23-January-2017

Senior .Net Developer
Source: Indeed
Details: Extensive Experience with NET OData, ADO.NET, LINQ, Entity Framework, ASP.NET MVC and ASP.NET Web Services. Strong SQL skills and familiarity with MS SQL Server...  More
3 days ago

Redmond, WA 06-April-2017

Senior Web Developer
Source: Indeed
Details: Net development tools. Asp.net mvc 3 or higher with Razor view engine. Indeed Hire is in partnership with MBM Inc....  More
2 days ago

Rocky Mount, NC 07-April-2017

Senior Full Stack .NET Web Developer
Source: Indeed
Details: ASP.NET MVC 4/5+:. 3+ years demonstrated experience in ASP.NET MVC 4/5+. Graphic Products is seeking a Senior Full Stack .NET Web Developer to join our Web Team...  More
5 days ago

Beaverton, OR 97005 04-April-2017

Senior Web/Application Developer
Source: Hobart Brothers Company
Details: BASIC DESCRIPTION: We are in search of a talented and energetic developer who will be responsible for solving the complex challenges presented by diverse  More
10 days ago

Troy, OH 45373 30-March-2017

.NET Developer Web (mid-level to senior)
Source: Indeed
Details: Angular2, ASP.NET, MVC, Gulp, Ruby. At EZ Prints, we make personalization possible for any online consumer with a full spectrum of technology, printing, and...  More
18 days ago

Norcross, GA 30071 22-March-2017

Application Developer
Source: TWO MEN AND A TRUCK®
Details: Application Developer Lansing, MI (Corporate) Summary: The Application Developer works as part of a team to develop and maintain web and client server  More
3 days ago

Lansing, MI 48911 06-April-2017

Microsoft Application Developer
Source: Indeed
Details: .NET, ASP.NET, MVC, Web Application Development Essential*. Bachelor’s Degree in Computer Science or MIS....  More
8 days ago

Rosemont, IL 60018 01-April-2017

Senior Software Developer .NET ASP.NET MVC
Source: Indeed
Details: Build new applications with .Net (C#) & ASP.NET MVC – heavy focus on client web portal. Reporting to the Vice President, Technology, the Senior Software...  More
9 days ago

New York, NY 10006 31-March-2017

Senior Web Developer
Source: Veson Nautical
Details: Exceptional coding and design skills, proficiency in ASP.NET MVC with C#, SQL, HTML5, JavaScript, jQuery, CSS3/SASS, and Single-Page Application Frameworks....  More
30+ days ago

Boston, MA 02116 09-March-2017

.Net Application Developer
Source: Indeed
Details: MUST HAVE: GREEN CARD OR U.S. CITIZEN NO CORP TO CORP Must be local to St. Louis, MO .NET Application Developer Are you a resourceful and motivated  More
13 days ago

St. Louis, MO 27-March-2017

Software Application Developer
Source: Indeed
Details: C#, MVC, HTML/JavaScript/CSS for designing and developing applications, UI, interfaces and web services. Builds new solutions with one or more of ASP.NET, MVC,...  More
15 days ago

Cincinnati, OH 45241 25-March-2017

Sr. Application Developer (C#, Angular.JS, Linq)
Source: Indeed
Details: C# .NET 4.0/4.5 (ASP.net, MVC, Web services (REST), Entity Framework, LINQ, Dependency injection). Sr....  More
16 days ago

Allentown, PA 24-March-2017

Full Stack Developer
Source: DISYS
Details: Proficiency with C#, ASP.NET MVC, EntityFramework, ADO.NET. Are you an experienced front-end developer who can deliver high-performance, intuitive UI design and...  More
11 days ago

Everett, WA 29-March-2017

Mobile Application Developer
Source: Indeed
Details: HTML5, CSS, JavaScript, jQuery, AJAX, ASP.NET, MVC, AngularJS, ReactJS, Meteor. DOE*....  More
19 days ago

Atlanta, GA 21-March-2017

Senior-Level Software Application Developer
Source: Indeed
Details: This is some of the most exciting .Net development going on including interesting ingredients such as C#, MVC, Angular, Azure automation, SSO, and more....  More
23 days ago

Nashville, TN 37203 17-March-2017

Mid to Senior level Demandware Developer
Source: createch
Details: Experience with web frameworks that implement MVC design pattern (Spring, Struts, Stripes, ASP.NET MVC, etc.). Mid to Senior level Demandware Developer....  More
24 days ago

San Francisco, CA 16-March-2017

Senior Software Engineer
Source: Patriot Software
Details: AngularJS, JavaScript , jquery, ASP.NET MVC. Use your extensive programming skills and problem-solving abilities to help Patriot Software, LLC build awesome...  More
2 days ago

Canton, OH 07-April-2017

Senior Software Engineer, Ed-Fi Alliance - Austin, TX
Source: Michael & Susan Dell Foundation
Details: The Ed-Fi Alliance is currently interviewing for a Senior Software Engineer to lead the efforts to support and enhance its core technology. This role reports  More
2 days ago

Austin, TX 78746 07-April-2017

Senior Full Stack Software Engineer
Source: MaxPoint
Details: Experience with ASP.NET, MVC, C# and/or Java. Senior Full Stack Software Engineer....  More
2 days ago

Austin, TX 78759 07-April-2017

Senior Full Stack Developer
Source: Indeed
Details: *Job Title: * Senior Full Stack Developer *Job Summary* * Under the general supervision of the Site Director, the Senior Full Stack Developer will join a  More
27 days ago

Modesto, CA 13-March-2017

Web Developer
Source: Indeed
Details: Required Qualifications: Ability to work in a dynamic environment and deal with ambiguity3-5+ years of experience designing complex web applications in ASP  More
3 days ago

Redmond, WA 05-April-2017

Senior C#/.NET Full Stack Developer
Source: Graphic Products
Details: 3+ years demonstrated experience in ASP.NET MVC 4/5+. We are looking for a Senior Full Stack Developer responsible for the ongoing development and advancement...  More
30+ days ago

Beaverton, OR 97008 09-March-2017

Lead .NET Developer – loan origination
Source: Indeed
Details: ASP.NET MVC, jQuery, JavaScript, JSON. C#, ASP.NET MVC, jQuery, JSON, AJAX, SQL Server, Entity Framework, responsive, mobile, etc, Envision product development...  More
1 day ago

Dallas, TX 75235 08-April-2017

Senior .NET Software Engineer
Source: LSQ
Details: Experience with ASP.NET MVC, HTML, CSS, JavaScript, and AJAX. Senior .NET Software Engineer....  More
10 days ago

Maitland, FL 30-March-2017

The post MUST Have C# Interview Questions and Answers – Part 2 appeared first on Web Development Tutorial.

MUST Have Core Java Interview Questions

0
0

Another article in series of Technical Interview Questions and Answers on Web Development Tutorial covering Core Java Interview Questions this time. You will find more detailed answers to mostly asked interview questions during a technical interview. Java Interview Questions and Answers

Java Interview Questions PDF version will be available later for download.


Following Related Technical Interview Questions and Answers will also be helpful.


Complete Java Interview Questions List

Courses Online

What is object oriented programming. How java differs from other object orienting programming languages like C++?

Object oriented programming, primarily known as OOP, is a programming paradigm, which simplifies the development of software using some key concept provided to make development easier and faster.  An object is something that has state and behavior. An object can have data, fields, methods. Objects can talk, access to other objects. Access would be granted based on the modifiers. A class in OOP stores information and demonstrate the information using methods, so class is basically blueprint of an object.

Let’s talk in brief about different components of Object Oriented Programming:

  • Object
  • Class
  • Encapsulation
  • Abstraction
  • Polymorphism
  • Inheritance

Object:

Object is something that has state and behavior. We can easily relate object to some real world objects like machine, car etc.

Class:

Class is basically a logical collection of objects. That can have multiple methods, variables encapsulated in it.

Encapsulation:

As the name suggests, encapsulation is basically to encapsulate multiple logically related things together in an entity that is called class and provide proper access modifiers to the variables, so that these can not be accessed directly from outer world.

Abstraction :

Consider a scenario, where you are writing some logic that you don’t want to expose to outer world, so we just expose declaration of the thing to outer world with help of interfaces so that the implementation will be completely hidden from outer world, Like we have a code that checks if   an number is palindrome or not, so we need not show our logic to calling code. We will just create an interface which will have a method and takes a parameter of which will a number and return a boolean based on our computation.  This is called abstraction, where the calling code does not know anything about the implementation.

Polymorphism :

If we go by definition, polymorphism means one name many forms. The same we apply while writing code in a language that is object oriented. So practically we create methods that have the same name but differs in parameters, it is called polymorphism. Where a single method name have more than one implementation. In java we use concepts like method overloading and method overriding to achieve the same.

Inheritance:

Whenever we write code, we always think of re-usability or extension of the code that is already written. So in inheritance an object takes all or some properties of the class that is parent to this.

We will talk in detail about these concepts. This is very basic overview about Object oriented programming and object oriented programming concepts.

Now lets talk about Java, so Java is an object oriented programming language that is extensively used in software world to create highly secure, robust software.

The main and most important feature of java that make it differ from other OOP programming languages is that Java is platform independent. When we say platform independent then it means write once and run anywhere. Java compiler creates a byte code that can be executed across JVM’s that can be Linux, that can be Windows, that can be MAC and so on.

If we talk about some key differences between C++ and Java then, although both languages are object oriented programming languages but still there are some key differences between these two :

  • C++ is platform dependent language, whereas Java is platform independent language.
  • C++ support multiple inheritance, whereas java removes multiple inheritance, since it can cause DOD that is Diamond of Death problem.
  • Pointers, C++ has support for pointers, Java also has support but java internally uses pointers. Programmer doesn’t have to write pointer code explicitly.
  • C++ does not have multithreading support, whereas Java provides support for multi-threading.

And so and so on, there are many differences between these two languages but these are the key ones.

Back to top

Explain installation and environment setup of java. Briefly explain what is JRE,JDK and JVM?

First we need to download the executable file from http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html as per our operating system. One done with download the executable file , run the file and it will install java to our system and on successful installation the folder structure will look like this:Java Installation

So we have downloaded and installed the Java Development Kit and we are ready to go to code. Before processing forward we need to set the environment variable so that when we run java from command prompt operating system will aware what kind of program to run.

To achieve this, we need to traverse through the path below:Java Path

Now click on Advance system settings link that is on the left pen of this page, this will open a window like this:Java Environment Variables

Now clink on the highlighted one, that is Environment variables. Upon clicking this a new window will open, under this , click on new under System Variables and create a new System Variable and name it to JAVA_HOME, against variable value we need to path of java installation directory that is with my system is:

C:\Program Files\Java\jdk1.7.0_79.

Lets set this and see how it looks:Java Home Setting

Click on OK button and we are done with creating a new system variable JAVA_HOME. Next step is to add this variable to path. Under the same system variables there will a variable path, edit it and add JAVA_HOME to path.

That’s it we are good to go to write our first java code. Lets check with command prompt if the installation and configuration went fine or not:Java Installation and Configuration

So I have checked java version with command prompt, if there is anything wrong with configuration or installation this command will not get successfully executed and there will be error message. So this is a small way to check installation of java.

JRE is basically shorthand for Java Runtime Environment. It is basically the Java Virtual Machine where your Java programs run on. It also includes browser plugins for Applet execution.

JDK is shorthand used for Java Development Kit, which is the Software Development Kit for Java, including JRE, and the compilers and tools (like JavaDoc, and Java Debugger) to create and compile programs.

Usually, when you only care about running Java programs on your browser or computer you will only install JRE. It’s all you need. On the other hand, if you are planning to do some Java programming, you will also need JDK.

JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed.

Back to top

What is polymorphism, Explain inheritance in java? Also explain overloading and overriding in java.

Polymorphism in object oriented programming is a concept where in an object can take one or more forms. Its like one name many forms. Any java object is elibigle to called polymorphic when an object “IS-A” kind of object. For example we have a parent class, then the eligible child classes can be Audi, BMW etc. So these child classes will extend the parent class that is Car and at the same time we can say Audi “IS-A” car, which makes Audi or BMW object polymorphic.

Lets understand the same with an example.

Here we will be creating a Car interface and this interface will have some methods that will be common to call cars.

package com.javatutorial.polymorphism;

public interface ICar
{
    
    void setEngineCapacity(String engineCapacity);
    
    String getEngineCapacity();
    
}

So we have created a simple interface that is called Icar. This interface has two dummy methods that will setEngineCapacity and getEngineCapacity.

Now lets create impl classes for this.

First let say we create AudiImpl class that will for car audi.

public class AudiImpl implements ICar
{
    @Override 
    public void setEngineCapacity(String engineCapacity)
    {
        //
    }

    @Override 
    public String getEngineCapacity()
    {
        return null;
    }
}

Now lets create BMWImpl class with our ICar interface implementation.

package com.javatutorial.polymorphism;

public class BMWImpl implements ICar
{
    @Override 
    public void setEngineType(String engineType)
    {
        //
    }

    @Override public String getEngineType()
    {
        return null;
    }
}

Lets create a Main class and try to understand the IS-A concept that is behind Polymorphism.

package com.javatutorial.polymorphism;

public class Main
{
    public static void main(String[] args)
    {
        ICar carAudi = new AudiImpl();
        ICar carBMW = new BMWImpl();
        
        getCarEngine(carAudi);
    }
    
    private static String getCarEngine(ICar car){
        return car.getEngineType();
    }
}

So first thing to notice is that when the objects are polymorphic in nature we can create the objects with Interface reference. Now both AudiImpl and BMWImpl implements the ICar interface, so we can say that these two objects “IS-A” ICar type.

Next thing comes DynamicBinding,  which is the calling code even doesnot know on what type object the call is made. See getCarEngine method, here we are just passing objects from our main method but we are receiving the object in ICar interface and we made call to our actual object. This is beauty of polymorphism.

Now lets talk in brief about overloading and overriding.

We call Overloading, when two or more methods in one class have the same method name but different parameters.

We call Overriding, when two methods with the same method name and parameters. But Import point to note is one of the methods will be present in the parent class and the other is in the child class. Overriding allows a child class to provide a specific implementation of a method that is already provided its parent class.

Back to top

What are different types of class loaders in java, explain class loading in java?

There are three kinds of class loaders in java :

  • Bootstrap (primordial)
  • Extensions
  • System

BootStrap or Primordial class loaders are class loaders that Loads JDK internal classes, java.* packages. Which will be defined in the sun.boot.class.path system property, typically loads rt.jar and i18n.jar.

Extensions class loaders are class loaders that Loads jar files from JDK extensions directory. Which will be defined in the java.ext.dirs system property – usually lib/ext directory of the JRE.

 

System class loaders are class loaders that Loads classes from system classpath Which will be defined in the java.class.path property, which is set by the CLASSPATH environment variable or –classpath  command line options.System Class Loader

Class loaders are hierarchical, and maintain visibility. Bootstrap class loader have no visibility on the class loaded by Extension class loader and Extension class loader have no visibility over the classes loaded by classpath loader or System class loader.

Class loaders use a delegation model when loading a class. They request their parent to load the class first before they attempt to load it by their own. When a class loader loads a class, the child class loaders in the hierarchy will never load the class again, here classloaders maintain uniqueness.

Classes loaded by a child class loader have visibility over the classes loaded by its parents but not vice versa.

Back to top

What is difference between Composition and Aggregation?

Composition and Aggregation are concepts where two objects use each other’s functionality. When one object use functionality or services exposed by other object it is called Association.

Composition is when one object or one class associated with other class or object in such a way that the class can not have any meaning if other class is not present. Lets take an example of Bike, a Bike  have many objects like Tyres, Engine, Gear and so on, but when the bike is destroyed all these objects will also destroyed. These objects can not function if there is no car object. This concept is called Composition in java.

Aggregation is when two or more objects are associated with each other in such a way that if any of the object dies or destroyed, other one will still exist. Lets take an example, A Company can have many employees, when a scenario where Company is closed, Employee can join other company as well.

We can say composition is stronger than Aggregation.  A relationship between two objects is known as  an association, and an association when one object owns other is known as composition, while when an association one object uses another object is known as aggregation.Composition Vs Aggregation

So as we can see, Composition represents the strongest form of relation between objects where as Aggregation denotes a slightly weaker relationship between objects then composition, Association is most general form of relationship.

Lets take a practical example of Composition. Here we will create a Class name Bike, and other class as Tyre, that will have brand variable in it. Lets create this:

package com.javatutorial.polymorphism;

public class Bike
{
    private final Tyre type;

    public Bike(){
        type  = new Tyre("MRF");
    }

}

class Tyre {
    
    private String brand;

    public Tyre(String brand){
        setBrand(brand);
    }
    
    public void setBrand(String brand){
        this.brand = brand;
    }
    
    public String getBrand(){
        return brand;
    }
}

So as you can see Bike class constructor is initializing Tyre class, so the lifetime of class Tyre associated with Bike object, and whenever Bike class will destroyed the Tyre class will also destroyed. These both objects have strong relationship with each other and this is what we call Composition.

Lets take example of aggregation, here we will have a class Company and the company will have list of Departments. Now the difference with this is, Company class is not responsible for initializing the department class, and when the Company class will be destroyed the same Department class will not get destroyed, since both have their own life cycle. This is what we call Aggregation.

import java.util.ArrayList;
import java.util.List;
public class Company
{
    List<Department> departmentList = new ArrayList<>();
}

class Department{
    String deptName;

    //getters and setters
}

Back to top

Continue with More Java Interview Questions and Answers:

What is difference between Abstract class and Interface in Java, also explain when to use what?

In OOPS there is a principle called Abstraction, that is to abstract things from outer world. To achieve this interface and abstract classes are used.  Abstract classes are the classes in java that can have methods in such a way that some can have implementation and some will not have. These unimplemented methods are called abstract methods and we use abstract keyword to declare such methods. Now thing is we can not instantiate the abstract class. One more thing with abstract class is that there must be one method that will be abstract in this class to be called as abstract, if there is no abstract then we can not write class as abstract, the compiler will complain. Same if there is any abstract method in there and we declare the class as normal class then also compiler will complain and force us to declare class as abstract. These classes are meant to written for inheritance.

On the other hand interfaces are also abstract classes but these are pure abstract classes. Like we talked about the declaration and definition of methods in abstract  class like some can have some  may not have implementation, but in interfaces methods that we write are 100% abstract, mean there will only be declaration and the class that is implementing the interface, that class will have to provide the implementation. Methods declared in interfaces are by default abstract. We write these both to achieve abstraction. Like let say I have a service, whose job is to insert some data in database after some processing, so I will only provide the service interface to outer world with some methods. The actual processing will be done in the implementing class of this interface and the implementation I will hide from outer world. This is beauty of abstraction.

Lets take example of how we write abstract class and interface.

Lets create an interface named IVehicle that will have some methods in it:

public interface IVehicle
{

    String getBrand();

    String getModel();

    String getEngineCapacity();

    String getFuelType();

}

So what we have done is we have created an interface named IVehicle with some methods in it, so every class that will implement this will have to provide implementation of these methods.

Now there are some methods, in which Brand, Model, EngineCapacity and FuelType will be provided. So now we will create one more level of abstraction and we will segregate the classes with one that have fuel type as diesel and one with fuel type as petrol. Why we will do this because all petrol cars object will not have to implement these methods. So we will create two abstract classes, lets create them:

public abstract class AbstractDieselVehicle implements IVehicle
{
    @Override
    public String getFuelType()
    {
        return "Diesel";
    }
}

public abstract class AbstractPetrolVehicle implements IVehicle
{
    @Override
    public String getFuelType()
    {
        return "Petrol";
    }
}

So now we have created a hierarchy and added one level of abstraction. Every petrol type vehicle will have to extend the AbstractPetrolVehicle and every diesel type of vehicle will have to extend the AbstractDieselVehicle abstract class and the class have to provide the implementation for rest of the methods. Below is the example for AudiA3 class that extends AbstractPetrolVehicle and this class has to provide the methods implementation.

Back to top

Explain serialization in java, what is use of Serial Version UID?

Serialization is the process wherein object is converted into bytestream and it’s state is saved, so that the object can be travel over the network. In order to achieve serialization java provides Serializable interface, that is marker interface. So any object on which we need to achieve serialization, the class must extend Serializable interface.

The process from which the byte stream converted to java object again is known as deserialization. In this the persisted file or the serialized byte stream is converted in java object.

public interface Serializable {
}

As we talked about the Serializable interface, the above pasted code is the code for this interface, as you can see there are no methods in this interface that’s why these type of interfaces are known as marker interface. They just let the jvm know that what type of object it is, rest JVM takes care of.

There can be a scenario wherein we don’t want to serialize all the fields of a class, and we want some fields should not get serialized, to achieve java provides one more keyword that is transient. All fields maked as transient will not be part of the serialization process.

Since serialization is the process where object’s state is persisted, so obviously the question comes in our mind, what about the static things. Since static variables are directly belong to a class and they don’t have anything to do with object. So the answer is that the static variables are not part of serialization  process as well, since first thing they belong to a class and not with an object and second is they are not part of object state.

SerialVersionUId , whenever we are going to serialize and our class implement serializable interface the IDE says something like this,

The serializable class doesn’t declare a static final serialVersionId of type Long.

So why it is always encouraged to use SerialVersionUID, basically this id is something unique that represents the object and whenever the object is being deserialized this id is being matched and if the id doesnot matches jvm throws InvalidClassException. This id is being placed just to ensure that the object is the same that it was at the time of serialization.

If one doesnot provide the serialVersionUId then the JVM automatically calculate the serialVersionUid and provide one. The same is calculated as the hashcode of the class and the membervariables and so.

One more question arises to our mind is that just above we talked about that the static variables are not part of serialization process since they doesnot belongs to the object state. And now we are talking about that the serialversionUid is used at the time of deserialization, meaning that the serialVersionUID is part of object byte array that is crated at the time of serialization. Its contradictory isn’t it ? Yes !! So what happens is that whenever the object is converted into the sequence of bytes at the time of serialization, then the serialVersionUid is added to the class metadata. And the same is travelled to the network so that whenever the deserialization process happenes the jvm quickly pickup the serialVesrionUID and matches it.

Lets take an example of the same:

First we will create a class name Car which is going to be serialize.

class Car implements Serializable{

    private static final long serialVersionUID = 3L;

    private String model;

    private String make;

    public String getModel()
    {
        return model;
    }

    public void setModel(String model)
    {
        this.model = model;
    }

    public String getMake()
    {
        return make;
    }

    public void setMake(String make)
    {
        this.make = make;
    }

    @Override public String toString()
    {
        return "Car{" +
                "model='" + model + '\'' +
                ", make='" + make + '\'' +
                '}';
    }
}

Lets serialize and deserialize, and check if we got the same object or not.

package com.javatutorial.serialization;

import java.io.*;

public class MainSerialization
{

    public static void main(String[] args) throws IOException, ClassNotFoundException
    {
        Car car = new Car();
        car.setMake("2016");
        car.setModel("Audi-A3");

        //Serialize
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.ser"));
        oos.writeObject(car);

        //Deserialize
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser"));
        Car objCar = (Car) ois.readObject();
        System.out.println("Car object : " + objCar);
    }

}

Lets run the code and see if got the same object that we serialize, with make as 2016 and model as Audi-A3.

Upon running the code what we got id:Serialization in Java

So we got the same object that we serialized. This was the code running example of serialization concept.

Back to top
This Java Tutorial Series is continued and you can find more Java Interview Questions in next Web Development Tutorial here.Courses Online

Top Technical Interview Questions and Answers Series:

The post MUST Have Core Java Interview Questions appeared first on Web Development Tutorial.

a MUST HAVE HTML5 Interview Questions and Answers – Part 2

0
0

It’s continuation of my previous post on HTML5 Interview Questions with detailed answers. In previous post we started to set a base knowledge for latest HTML standard i.e HTML5. Later discussing about HTML5 new elements and more details about Graphics related concepts including SVG and Canvas.

I’ll recommend to read the following posts on HTML5 Interview Questions:

Questions are moved to other Parts as mentioned above.

Here we will continue exploring more HTML5 concepts with the help of Interview Questions.

HTML5 Interview Questions List – Part 2

What is localStorage in HTML5?

In order to store data locally, HTML5 supports for localStorage object. It stores data for a longer time in a client browser but it doesn’t lost data even if browser is closed. This purpose was achieved previously with the help of Cookies.

localStorage has following advantages as compared to using Cookies:

  • localStorage has better performance even for larger amount of data.
  • localStorage can store data for longer period.
  • localStorage is more secure as compared to cookies.

Back to top

What about browser support for localStorage in HTML5?

Browser support for localStorage in HTML5 is as follows:

  • Chrome 4
  • IE 8+
  • firefox 3.5+
  • Safari 4
  • Opera 10.5

Back to top

Free Online Test

<<< Previous: HTML5 Interview Questions – Part 1

Other Related Articles:

Top 10 Interview Questions and Answers Series:

The post a MUST HAVE HTML5 Interview Questions and Answers – Part 2 appeared first on Web Development Tutorial.

Interview with Rahul Sahay –“ASP.NET MVC Code First”

0
0

I am excited to introduce my guest today, Rahul Sahay, Owner of a very active Technological Facebook group “ASP.NET MVC Code First“, a decent blog and Author of following books:

  • Hands-On with ASP.NET MVC Covering MVC6
  • Building Single Page App with ASP.NET MVC5 and AngularJS

Blog My View (http://myview.rahulnivi.net) which is nearing 1.5 Lac visits. 70K visitors visit site on regular basis. Facebook group members count reaching 13,000. Congratulations on that Rahul :)
Imran: Rahul, I have given a short introduction about you, your blog and books. Please tell us more about you and what you do?

Rahul: Thanks for kind introduction. Frankly speaking, last year when I started writing my blog; I started on 1st Jan 2014; that was last year resolution to spread the word. Later on I realized that people started liking my articles as my articles basically focus on How To stuffs? rather writing high level stuffs.

Imran: When did you start your Facebook group “ASP.NET MVC Code First”, and why did you create it? What was the motivation or inspiration behind it?

Rahul: Again, that get started last year to engage more people from same field. It’s like collect all the fishes from different ponds and put them in a single pond to have more engaging and interactive discussion on Facebook group.

Imran: What do you feel makes your Facebook group special?

Rahul: Hmmm. That’s a typical question. However, still with Facebook group long way to go as there are couple of groups on the top of this. But, special thing about this, we encourage people to cascade Job opportunities as well so that freshers/experienced people at the end get benefited.

Imran: What are some of the hot topics that seem to always be discussed within the group?

Rahul: Off course, MVC is the key thing. But, I also encourage people to talk about other technologies as well like AngularJS, WCF (Windows Communication Foundation), Web API, Entity Framework, Azure, Other JS testing patterns like Jasmine, QUnit and many more stuffs which is really hot cake in the market.

Imran: For someone new to this group, how do they get the most out of it?

Rahul: He/She need to be active not all the times. But, whenever they login, once check the discussion tab there, so that they will come to know latest happenings on the group.

Imran: For our audience, please discuss in detail about the books you have written?

Rahul: I start in a descending order. So, the latest one which I have written is actually marriage of tons client/server technologies.
Here, I have used technologies like ASP.NET MVC which is basically base framework for the application.

  • Web API:- Off Course in order to data transportation; I found Web API being the best. Since, it embraces stateless design out of the box and built in HTTP verbs support the same.
  • AngularJS:-This is one of the most talked technology in the neighborhood today. I find, Angular JS is the most suitable one for building SPA (Single-Page Applications).
  • QUnit:- This one I have used for testing my Web APIs. QUnit is one of the most popular JavaScript libraries used by JQuery team to write their test cases.
  • Jasmine:- Again, Jasmine is a different JS testing library used for writing test cases for AngularJS. I have chosen this one as angular team also uses the same one to write their test cases.
  • Unit of Work Pattern:- I am fan of this design technique. It always gives me ability to aggregate the changes or keep the changes at one place and use at multiple place.
  • Factory Pattern:- Under the hood of UOW, I am using factory pattern for initializing the factors like dbContext, off course, for the 1st time and then in subsequent call, it will be addressed by the same instance until site is closed.
  • Solid Principles:- SRP is one of the most used technologies from Solid principle. I usually keep my dependencies per class basis. This also helps me in writing clean Unit test cases.
  • Chutzpah Project:- This one I installed from Extension and Updates as this helps to integrate JS Test cases under the hood of MS Test runner. So, what will happen as soon as you click run all?, This will run both managed test cases and un-managed test cases under the same hood.

I have also written book on MVC. That is Hands-on with ASP.NET MVC. This basically talks about MVC right from the scratch till professional level Implementation.

Imran: Please discuss about your blog. What major areas are focused and how a developer can take maximum benefit from it?

Rahul: Frankly speaking I have started the blog as in for my learning purpose means as a online repository which I can refer at any point of time. But, later on I realized that people are coming to my blog and reading my article and providing feedback for the same. This actually boosted my confidence and then I decided, OK I will go ahead and make this a regular blog which will talk not only about Microsoft Technologies but discuss latest trend in the market like Angular. Till date, I think I have written 163 articles. And in about 1 year response is very good.

Imran: It’s really amazing Rahul. What are your future plans about introducing more exciting things for your group members? Also, Is there any specific topic you are planning to write a book about?

Rahul: Exciting thing to me is always talk about latest technology and share the same with group members. it’s very important to have the implementation knowledge at least on these new technology. Web is changing rapidly. People now converging towards JS framework more rather than managed code environment like .Net or Java. So, in future I’ll be talking more on ASP.NET 5 which is again a great change in this area and then off course Angular and Typescript. Also, I would like to focus on Azure and its capabilities. Next book which is coming is on WCF.
It is basically enterprise edition. So, here readers will experience end to end experience right from the scratch. Again this book is very deep dive. I think people will love it.

Imran: Finally, What do you suggest all your group members and .Net developers at large to improve their skills?

Rahul: Learning is important and learning new skills, new improvements of existing language like C#, and implementing the same in your existing project will help any person to improve the skills. This is very important because these days even client is very demanding, they don’t want to invest or focus on old stuffs.

Imran: Thanks a lot Rahul. I really feel proud to have you with us and sharing your thoughts. Thanks once again.
Exam 70-486


More You Must Read about ASP.NET MVC & Related

Top 10 Interview Questions and Answers Series:

The post Interview with Rahul Sahay – “ASP.NET MVC Code First” appeared first on Web Development Tutorial.


25 Best Tools for HTML5 Developers

0
0

Developers have been using HTML (HyperText Markup Language) for many years to develop the web pages. HTML5 is the latest version of HTML which has many new features to change the world of web development and design. The mobile internet user is growing at a faster pace across the world and therefore, it is a must for your website to have mobile responsiveness. HTML5 provides you with the feature to develop mobile-friendly websites. Being one of the most cost-effective languages for mobile applications, HTML5 has also enhanced the user experience largely. If you still want to know more, here is a list of advantages of HTML5 web development:

  1. Improved Accessibility
  2. Audio and Video Support
  3. Optimized and structured code
  4. Highly interactive websites
  5. Cross-browser compatibility
  6. Mobile responsive sites


This eventually leads to huge demand for professional HTML5 developers in the market. That being said, any new technology needs to be learned first in order to master it. Considering this fact, here is a list of the 25 best tools for HTML5 developers:

1. Animatron

Whether you are a newbie or a professional, Animatron lets you make your website highly interactive. And the best part is that you do not need to code. You just create your animations and save them on the cloud which can be accessed anytime and anywhere. Once, you have created your animation, you can export it to HTML5, GIF, and video formats. It is said that two heads always give better ideas, so you can invite your project team-mates to work on the same window by sharing the URL.
HTML5 Animation
You can watch all the changes as they are happening from the other side. In case, you do not want to share your project with anyone you can make it private. Choose a plan that suits you can go with one of the best tools.
LINK: https://www.animatron.com/

You can find a Comprehensive list of HTML5 Interview Questions and Answers here.

2. Purple Animator

Purple Animator is the best choice if you want to create designs for multiple platforms like Android, iOS, Kindle etc. You can create all the interactive app contents with the help of Purple Composer or, Purple Animator.

LINK: http://www.purplepublish.com/purple-animator/

purplepublish

3. INK

With the INK tool, you can create responsive HTML5 emails that can be accessed anywhere and on all devices or client including Outlook.

LINK: http://foundation.zurb.com/emails.html

ink

4. Initializr

It provides you with the templates from which you can choose and kick-start your project. You can also select the responsive template.

LINK: http://www.initializr.com/

Initializr

5. Create

It is a web-editing interface in which you can edit anything on Content Management Systems. It provides you a comprehensive HTML5 based environment in which you can edit any content you wish to and later you can push the changes to the CMS.

LINK: http://createjs.org/

create_js

6. HTML5 Maker

No other tool can win against HTML5 Maker when it comes to animations and web graphics. You do not need to create designs separately in Photoshop for the text or photos effects. HTLM5 Maker lets you do it all on one tool.

LINK: http://html5maker.com/#/

html5maker1

7. 99LIME

Joshua Gatcke runs this website to help the web designers learn creative web designing. You can learn tips and tricks of web designing to stand out of the crowd.

LINK: http://www.99lime.com/

99lime

8. HTML5 Bones

HTML5 Bones is a boilerplate for HTML5 websites. There are no JavaScript libraries included in it so it is very easy and basic to use.

LINK: http://html5bones.com/

HTML5 Bones

9. Mixeek

It is a web-based tool using which you can create interactive animations. It uses both HTML5 and CSS3. Not only this, it is also free and can be used easily.

LINK: http://www.mixeek.com/

mixeek

10. Edge Animate

It is a product by Adobe which is known for the best designing frameworks. With Edge Animate, you can create interactive HTML animations for web, digital publishing, rich media advertising etc. All these can be easily accessed on both web as well as mobile.

LINK: http://www.adobe.com/in/products/edge-animate.html

edge animation

11. Literally Canvas

Literally Canvas is an open-source HTML5 drawing widget. Using this extensible widget, you can do sketching and do anything with the end results.

LINK: http://literallycanvas.com/

12. RazorFlow

If you are looking for a tool to design Dashboards in PHP and JavaScript, then RazorFlow is what you need.

LINK: https://www.razorflow.com/

13. Onsen UI

Onsen UI is a custom elements based HTML5 UI framework that can be used for Cordova UI development. It enhances the user-experience and provides native-like performance.

LINK: http://onsen.io/

14. Google Web Designer

Create outstanding visual experience without worrying about the backend part with Google Web Designer. You can design creative HTML5 designs and can implement the same on any device.

LINK: https://www.google.com/webdesigner/

15. HTML Test

I am sure you would want to check the compatibility of your HTML5 with your browser. HTML Test checks your browser’s over functionality

LINK: http://html5test.com/

16. TUMULT

Tumult is also one of the apt choices for creating interactive web content and designs. It provides support on desktops, mobile devices and iPads. It provides you multiple browser support, CSS effects, ability to embed easily and you can also share it via Dropbox.

LINK: http://tumult.com/hype/

17. Stitches

You can create both sprite sheets and spreadsheets by just dragging and dropping the images on the tool. A sprite sheet is created by combining multiple small images or icon into a larger image. Try it yourself as it provides a demo.

LINK: http://draeton.github.io/stitches/

18. Sencha

Sencha is web application development platform. You can create n number of cross-platform applications that provides native-like user experience. After designing and developing the application, Sencha also gives you the power to manage the app yourself. You can first go with the free version and then get the premium one as per your requirement.

LINK: https://www.sencha.com/

19. Moqups

Next time you need to create designs, wireframes, prototypes or any UI concept; Moqups is the one solution for all. Simple drag and drop function makes this nifty HTML5 App highly usable.

LINK: https://moqups.com/

20. Mugeda

You can create HTML5 animations, cross-platform apps, analyze traffic, media campaigns and much more with this professional IDE i.e. Mugeda. It provides you with a Mugeda JavaScript API, using which you can create web or hybrid apps.

LINK: https://www.mugeda.com/

21. ShareDrop

ShareDrop is a clone of Apple AirDrop Service but in HTML5. This tool lets you share the files directly without the need of uploading them on the server.

LINK: https://www.sharedrop.io/

22. Cloak

If you are developing an HTML game, then Cloak is a must as it acts as a network stratum. It provides with features like resuming when reconnecting and timers.

LINK: http://incompl.github.io/cloak/

23. CutJS

For the cross-platform game-development use Stage.js which is open-source and lightweight HTML5 JavaScript library.

LINK: http://piqnt.com/stage.js/

24. Framework 7

It is an app development framework with you can create robust iOS and Android applications with the native look and feel. It uses HTML for the application development, therefore reducing the cost of development.

LINK: http://www.idangero.us/framework7/#.Vk21cnYrLIU

25. Puzzle Script

Puzzle Script is used to create complex puzzle games. It is an editor in which you can build the game, export it and share too.

LINK: http://www.puzzlescript.net/editor.html

With all these best tools you create the best websites or mobile applications for any purpose including gaming. Choose what suits you the best and then create the best solutions.

Author Bio:

Nirdosh has a knack for exploration and loves to dig into WordPress, and share her knowledge with others. She is currently working with WP Daily Themes. She is also a programmer, a writer and a motivational speaker.

Are you looking for a Web Development Jobs in Gulf Region? Please follow below:
Top Gulf Jobs

The post 25 Best Tools for HTML5 Developers appeared first on Web Development Tutorial.

Top 20 Entity Framework Interview Questions – MUST HAVE

0
0

This post is about Entity Framework Interview Questions that will explore various features, concepts and FAQs regarding Microsoft Entity Framework. It’s basically a collection of most frequently asked Entity Framework Interview Questions for developers. You can also explore some practical solutions implementing Entity Framework here:

You are working with WebDevTutorial and building an ADO.NET Entity Framework application for a client. You need to validate the conceptual schema definition language (CSDL), store schema definition language (SSDL), and mapping specification language (MSL) files. Which Entity Data Model tool can you use? (Each correct answer presents a complete solution. Choose all that apply.)
  • A. EDM Generator (EdmGen.exe)
  • B. ADO.NET Entity Data Model Designer
  • C. Update Model Wizard
  • D. Entity Data Model Wizard
  • E. All of Above
  • F. None of Above

For a complete online test and Practice Exams on Web Technologies, Click Here.

 Correct Answer: B, D

Entity Framework Interview Questions List

More Entity Framework Interview Questions for beginners and Experienced

What is Entity Framework?

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

Microsoft introduced Entity Framework with .NET Framework v3.5 Service Pack 1 supporting basic Object Relational Mapping support but later EF4 was introduced as second version aligning with .NET Framework v4.0.
Back to top

What are the advantages of using Entity Framework?

Main advantages of Entity Framework are:

  • Separation of Concerns (SoC).
  • LINQ is used as a common syntax for all object queries.
  • Code Auto-Generation.

Back to top

What is Entity Framework(EF) Core?

Entity Framework 7 rebranded as Entity Framework Core 1.0 is basically an object-relational mapping framework that allows us to communicate with database using .NET objects. It’s a lightweight, open-source and extensible framework for targeting .NET Core applications.Entity Framework Core

Entity Framework Core 1.0 has following additional features:

  • Cross Platform i.e. can work with .net core application built for MacOS or Linux.
  • Designed for disconnected/web services.
  • Entity Framework Core is cloud optimized.
  • EF Core is Device Optimized as being lightweight can work with SQLite.
  • Support for relational and non-relational databases.
  • EF Core also has Fluent API that enables a user to override the OnModeCreating strategy on a user’s context and makes it easy to figure the convention model.
  • Built-In convention that effectively builds an initial model based on the entity classes.
  • The EF Core features data annotations that are added to entity classes or properties to influence the EF model.
  • It also has Snapshot change tracking properties based on recording the initial values of an entity as it is retrieved from the database.
  • Notification change tracking enables a user’s entities to signal the change tracker in case property values are modified.
  • Connection resiliency that automatically retries any failed database commands. Connection resiliency comes in handy for connection to SQL Azure which is prone to transient failures.

There are many key features those were available in EF 6.x but not included in Entity Framework Core 1.0.

  • No Lazy Loading.
  • Group By Translation – If query includes a group by clause, it will be omitted.
  • Not Supporting stored procedures.
  • No Graphical Modeling Tools supported.
  • Spatial Data Types (a wrapper around a COM library).
  • Simple Command Interception.

Back to top

What is the Nuget Package console command to install Entity Framework, if it’s not there in you project at that time?

Following is the Nuget Package console command to install Entity Framework:

Install-Package EntityFramework -Version 6.1.1Install Entity Framework -Version 6.1.1
Back to top

How to Install Entity Framework via NuGet Package in Visual Studio?

It’s quite simple to install Entity Framework via Nuget for our project in Visual Studio. For example, If I have just created a new project and want to install Entity Framework, below step by step approach will be helpful.

  1. Right click on the project and choose “Manage NuGet Packages…”.Manage NuGet Packages
  2. On Installation page, choose “Browse” Tab from top left and then enter “Entity Framework” in search box below that and click on search icon. It will list down all Entity Framework related results below. Installing Entity FrameworkAs you can see, we have selected Entity Framework and all details (including version, author, License, Date Published etc.) of the selected item are displayed in right area.
  3. In above screenshot, click on Install button. It will ask for a Review Changes going to be done, confirm by clicking “YES”.Review Install EF
  4. It followed by a License Acceptance confirmation. Just confirm by clicking “I Accept”.License Acceptance EF
  5. Once you accept the License, it will complete the installation displaying details in Visual Studio Output Window as shown in below screenshot.Entity Framework Installed Finally, you can see the successful installation message in Output Window. Once the installation is done successfully, you can see EntityFramework and EntityFramework.SqlServer in References of our project.

Back to top

Where do we use Virtual classes in Entity Framework DbContext Models?

We use Virtual classes in Entity Framework in context class where we define DBSet of corresponding table. As we can see easily in below code sample for Students and Departments:
Entity Framework Interview Questions Virtual Classes
Back to top

Entity Framework uses DbContext, How is it different from Object Context?

DbContext can be used for code first while Object Context doesn’t. It exposes the most commonly used features of ObjectContext.
Back to top

What’s new in Entity Framework 6?

  • Customizing Code First Conventions.
  • Logging of database commands.
  • Stored Procedure Mapping.
  • Asynchronous Queries and Save support.

Whats New In EF6

With EF6, in applications with lots of tables and relationships defined, our context objects open faster. We should also be better insulated from dropped connections (at least, if the drop is transient and not permanent — nothing is going to help there).  EF6 also generates SQL faster from LINQ queries than before (though it’s the same SQL that’s being generated as in earlier versions of EF, so your actual data access won’t be any faster or slower).
Back to top

Can we access a model in Entity Framework without primary key defined?

No, but we can access data.

Using Primary Key:

Student student = db.Students.Find(id);

Without Primary Key:

Student student = db.Students.Where(x=>x.StudentName==”Ahmad”);

Back to top

Why do we use Lazy Loading in Entity Framework?

Entity Framework facilitates us to avoid huge, deep, highly-relational queries, so that the data will not heavy on the web.

Student student = db.Students.Find(id); //----> Step 1: Student record will load.
if(student != null){
	student.Department; // ---> Step 2: Department details will be loaded.
}

Note: As by default, lazy loading option is enabled in Entity Framework but that can cause major performance issues in some scenarios as below:

var students = db.Students.ToList(); // no department will be loaded.
foreach(var student in students)
{
	student.Department; //department will be loaded here.
}

As for above scenario, student.Department will load department from SQL Server by firing a new SQL query for each iteration and it’s a performance degradation in case of large number of records.
We can disable Lazy loading (or in other words, enable eager loading) by using the following code:

db.ContextOptions.LazyLoadingEnabled = false;

Back to top

Why DB Context models object disposal is important in Entity Framework?

Until it’s disposed, it will be holding resources that aren’t in. If not disposed then Garbage collector will free the space but in some instance it holds up.

Calling dispose method to clear memory.Dispose in Entity Framework
Back to top

Can we do an insertion and deletion at the same block of code and then Apply save changes to them in a statement in Entity Framework?

Yes, WE CAN by using the below piece of code:

Save changes in Entity Framework

Here the student record will insert to db but not physically. When we call SaveChanges method then it actually insert in db and commit the transaction. If we delete before committing transaction nothing will change in database.
Back to top

What are the development approaches are supported in Entity Framework?

Following are the development approaches available in Entity Framework. Implementation of each approach is given in detail in separate Entity Framework Tutorial:

  • Code First Approach – where code defines the database. Entity Framework handles creation. A complete detailed implementation of Entity Framework Code First Approach here.
  • Database First Approach – regular approach used where database is first created or already exists.
  • Model First Approach – where model is drawn first that further generate database scripts.

Development Approaches in Entity Framework
Back to top

If we have not followed proper conventions in Code First approach, then how we can mark a field/property as primary key?

An important point to remember about EF Code First approach; we have to follow proper convention for a primary key, means Entity Framework expects ID combined with Entity Name. In our case, above referred Code First Example, we have two entities (i.e. Category and Product) and for both of these entities, we used proper convention for primary key i.e. CategoryId and ProductId.

But in case we used something different i.e. “UniqueCategoryIdentifier” or “UniqueProductIdentifier”, then we have to tell that this is our primary key column and this can be done using a simple attribute i.e. “Key” as follows:

public class Category
{
   [Key] 
   public int UniqueCategoryIdentifier { get; set; }

   public string CategoryName { get; set; }

   public ICollection<Product> Products { get; set; }
}

public class Product
{
   [Key]
   public int UniqueProductIdentifier { get; set; }

   public string ProductName { get; set; }

   public decimal Price { get; set; }

   ....
   ....
}

If we don’t follow the convention as well as not using the “Key” attribute, then will end up with following error.

"One or more validation errors were detected during model generation: System.Data.Edm.EdmEntityType : EntityType 'Category' has no key defined. Define the key for this Entity Type........"

Note: It’s always recommended to use proper convention or use “Key” attribute to tell Entity Framework about our primary key field.

Back to top

How we can enforce number of characters (minimum or maximum) for a field using Entity Framework Property Annotation method?

We can easily use property annotation of MinLength and MaxLength to enforce minimum or maximum number of characters for a specific field respectively. For example, If we want to have minimum and maximum number of limit for CategoryName field for Category Entity (say minimum 10 and maximum 100 characters). Below is the way to use, MinLength and MaxLength:

public class Category
{
   [Key] 
   public int UniqueCategoryIdentifier { get; set; }
 
   [MaxLength(100, ErrorMessage="Maximum of 100 characters allowed")]
   [MinLength(10, ErrorMessage="Minimum of 10 characters required")]
   public string CategoryName { get; set; }
 
   public ICollection<Product> Products { get; set; }
}

Back to top

How we can use a property for an Entity that is not mapped to database in Code First Approach?

In Code First Approach, all properties are normally mapped to database. But in certain scenarios, if we don’t want a specific property to be mapped to database, Entity Framework provides us with NotMapped attribute for annotation.

Let’s take a practical example, we have an entity i.e. Product and we want to have a ProductCode that will not be mapped to database. So, we will do the following to achieve in Code First Approach.

public class Product
{
   [Key]
   public int UniqueProductIdentifier { get; set; }
 
   public string ProductName { get; set; }

   [NotMapped]
   public string ProductCode 
   {
	get{
		return UniqueProductIdentifier + "-" + ProductName
	}
   }
 
   public decimal Price { get; set; }
 
   ....
   ....
}

Back to top

What is the query syntax we use to query an ADO.NET Entity Data Model?

We can use LINQ to Query ADO.Net Entity Framework. For Example:

Entity Data Model
Back to top

Is LINQ a feature of Entity Framework?

Yes, following is the example to get student record from Section A.

LINQ feature in EF6

The same in Entity Framework:

Student student = db.Students.Where(x=>x.Section==”A”);
Back to top

Does Default New Project Creation under Internet Template Category of ASP.NET MVC have any DB Context Ready while creating the project?

Yes, There is, as we can see in the below screenshot:Template Category For MVC
Back to top

If you provide the Primary Key value while inserting record to Entity Framework, will that execute fine, or will it throw an error while the adding statement?

Yes it will threw error if same a record present with same data. If identity is set then it will give error in any case.Insert In EF6
Back to top

What are the properties or Database Elements get copied in Dataset when Clone method is used?

It will create a new object with same properties with a new instance.Clone Method in EF6
Back to top

What is the role of a Self-Tracking Entities?

Self-tracking entity allows you to add code generated item:Self Tracking Entities in EF6
Back to top

Can you describe the feature of split entity in Entity Framework?

Entity splitting gives us the ability to take an entity in our model and split this entity into multiple database tables. When we query an entity, Entity Framework will create a query that Automatically joins the related physical tables for us.
Back to top

What is the role of Entity Container in Entity Framework?

Entity container is a logical grouping of entity sets, association sets, and function imports.  The following must be true of an entity container defined in a conceptual model:

At least one entity container must be defined in each conceptual model.  The entity container must have a unique name within each conceptual model.

Entity Container in EF
Back to top

Do we need to define any assembly references of entity framework if we use in web.config file?

Yes, that is necessary:web.config for Entity Framework

Back to top

More Entity Framework Interview Questions including Entity Framework Core

LINQ to SQL Vs Entity Framework?

Following table clearly explains the difference between LINQ to SQL Vs Entity Framework:

Entity Framework LINQ to SQL
Work with any database including SQL Server, Oracle, MySQL, DB2 etc. Works but limited to SQL Server.
Entity Framework works well in enterprise scenarios where requirement is to develop a loosely coupled application. LINQ to SQL is good in rapid application development scenarios but follows a tightly coupled approach.
Entity Framework maintain a conceptual model that actually maps to storage model using a mapping. So, it’s possible that multiple EF classes map to one table or multiple tables map to one EF class. A LINQ Entity directly maps to one SQL Server table only. In order to maintain a relationship, it generates a .dbml file.
Can generate database from model and it’s a key feature. Generate database from model is not possible.
Back to top

How to handle transactions in Entity Framework 6

Transaction being a single unit of work that are either successful or failed has really important for an application that is developed using Entity Framework. Entity Framework supports transactions in following ways and this Entity Framework 6 Interview Questions demonstrate the same:

The “SaveChanges()” method in Entity Framework operates within a transaction and saves results of the work. This is how the data integrity is being ensured.

In Entity Framework 6.0, two new APIs are used to maintain the transaction:

1. DbContext.Database.BeginTransaction: Below we can find source code to understand that how different operations are combined within the same transaction and further are all committed or rollbacked. This method also allows us to specify the isolation level for the transaction.

using (EFModelFirst_DemoContainer context = new EFModelFirst_DemoContainer()) 
{ 
      using (var transaction = context.Database.BeginTransaction()) 
      try 
      { 
            Category c = new Category(); 
            c.CategoryName = "Mobile"; 
            context.Categories.Add(c); 
            context.SaveChanges();

            Product p = new Product(); 
            p.CategoryId = c.CategoryId; 
            p.ProductName = "HTC"; 
            p.Price = "15000"; 
            context.Products.Add(p); 
            context.SaveChanges();
  
            transaction.Commit(); 
       }
       catch (Exception ex) 
       { 
            transaction.Rollback(); 
       } 
}

2. DbContext.Database.UseTransaction: It allows DbContext to use a transaction that was stated outside of the Entity Framework. It means using this API we can use any existing transaction with Entity Framework.

It is used when sometimes we must use an existing transaction that is started outside of the Entity Framework.

public EFModelFirst_DemoContainer() 
: base("name=EFModelFirst_DemoContainer") 
{
}
(SqlConnection con = new SqlConnection("connectionString")) 
  { 
     con.Open(); 
     using (var transaction = con.BeginTransaction()) 
     { 
         using (var transaction1 = context.Database.BeginTransaction()) { 
           try 
           {  
               Category c = new Category(); 
               c.CategoryName = "Mobile"; 
               context.Categories.Add(c); 
               context.SaveChanges();

               Product p = new Product(); 
               p.CategoryId = c.CategoryId; 
               p.ProductName = "HTC"; 
               p.Price = "15000"; 
               context.Products.Add(p); 

               context.SaveChanges();
               transaction.Commit(); 
            }
            catch (Exception ex) 
            { 
               transaction.Rollback(); 
            }
       } 
  }

Back to top

  • Learn ASP NET MVC 5 step by step [Maruti Makwana, Corporate Trainer] 28 Lectures, 2.5 Hours Video, Intermediate Level
    Very easy to learn video series on Asp.Net MVC 5 Specially for those who are familiar with Asp.Net Web forms.
  • AngularJS for ASP.NET MVC Developers [Brett Romero] 10 Lectures, 1 hour video, Intermediate Level
    The Fastest Way For .NET Developers To Add AngularJS To Their Resume
  • ASP.NET with Entity Framework from Scratch [Manzoor Ahmad, MCPD | MCT] 77 Lectures, 10 hour video, All Level
    Latest approach of web application development
  • Comprehensive ASP.NET MVC [3D BUZZ] 34 lectures, 14 Hours Video, All Levels
    From zero knowledge of ASP.NET to deploying a complete project to production.

Concluding Notes:

Again, this is my prepared list of important Entity Framework Interview Questions but reader can suggest/contribute more related concept area. I’ll be more happy to add those questions/concepts and update the Entity Framework Interview Questions list.

More Related Articles:

Top Web Developer Interview Questions and Answers Series:

ASP.NET MVC Jobs [Updated Daily]

Top ASP.NET MVC Jobs

Developer Lead - ASP.NET, C#
Source: Excell
Details: MVC). ASP.NET MVC, C#, WebAPI. As part of a leading IT managed services specialist with more than 12,000 associates worldwide, we rely on the personal...  More
1 day ago

Redmond, WA 98052 10-May-2017

Sr .NET Developer / Moible Development (Conyers)
Source: Synergy Hire LLC
Details: MVC. In this role you will be working on both front-end and back-end web development utilizing C#, ASP.Net MVC, Entity Framework and SQL Server on the server...  More
9 days ago

Conyers, GA 01-May-2017

Lead .Net & Mobile Developer
Source: Posh Technologies
Details: Visual Studio 2013+, C#, ASP.NET MVC 5 and Web API 2. 5+ years of working experience with C#, ASP.Net MVC, SQL Server, JavaScript....  More
6 days ago

Redmond, WA 04-May-2017

Lead .NET Developer with Public sector
Source: Indeed
Details: Hi Hope you doing great. Please find the below requirement, if you are comfortable with the below requirement send me your updated resume ASAP. *Job Title:...  More
1 day ago

Harrisburg, PA 09-May-2017

Sr Lead .Net Developer
Source: Indeed
Details: *Direct Client Requirement* *VISA copy, DL Copy and Passport Number (OR) Passport Copy Needed.* *Job Title: Sr Lead .Net Developer* *Location: * *Harrisburg...  More
2 days ago

Harrisburg, PA 08-May-2017

contract Sr .NET Developer
Source: Indeed
Details: ASP.NET or ASP.NET MVC:. 5-7 years of proven experience using Microsoft technologies including ASP.NET and ASP.NET MVC, IIS8, Azure, and SQL Server;...  More
2 days ago

Irvine, CA 92606 08-May-2017

Mid level .Net Developer
Source: Indeed
Details: IT Solutions Consulting, a full-service consulting firm in Fort Washington, PA, needs a mid-level ASP.NET software developer for a full-time position at our  More
8 days ago

Fort Washington, PA 19034 02-May-2017

Mid Level C#/ASP.Net Developer
Source: Indeed
Details: 2+ years' experience with ASP.NET MVC, at least 1 year using the 4-4.5 framework. Ideal candidate will have 2-5 years of web-based application development and...  More
12 days ago

Nashville, TN 28-April-2017

Software Engineer .NET, C#
Source: American College of Healthcare Executives
Details: Utilize ACHE’s evolving technology stack including Visual Studio, C#, MS SQL Server, ASP.NET, MVC, XML/XSLT, JavaScript, and jQuery....  More
15 days ago

Chicago, IL 60606 26-April-2017

Lead .Net Developer
Source: conrep
Details: Object Oriented Programming, WCF, VB.Net, Visual Studio 2008, Enterprise Library, MSMQ, Security Fundamentals, SSIS, SSRS, ASP.NET, MVC 4.0, HTML, SQL 2008 or...  More
1 day ago

Dimondale, MI 48821 09-May-2017

Lead .Net Developer
Source: Indeed
Details: MVC 4.0 or higher .NET technologies and Framework - 3Years. Object Oriented Programming, WCF, VB.Net, Visual Studio 2008, Enterprise Library, MSMQ, Security...  More
1 day ago

Lansing, MI 09-May-2017

Sr Lead .Net Developer
Source: Indeed
Details: ASP.NET MVC - 5 Years. The ideal candidate would have experience with Microsoft Test Manager or other similar testing tools, and be responsible for writing unit...  More
3 days ago

Harrisburg, PA 08-May-2017

Software Engineer C#/ASP.NET MVC/JavaScript
Source: Cormant, Inc.
Details: You will be working on full stack development including Marionette client, and a C# MVC architecture with NHibernate/RDBMS as the back-end....  More
19 days ago

San Luis Obispo, CA 21-April-2017

Junior to Mid-level .Net Developer
Source: Indeed
Details: Experience with the MVC pattern for web development. US Citizens or Greencard that do not require a Visa Sponsorhip for Full-Time Employment*....  More
22 days ago

Englewood, CO 18-April-2017

Lead .Net Developer
Source: Indeed
Details: Previous experience with the .NET Framework, C#, ASP.NET MVC, and SQL Server. Required 3+ years’ experience in development with experience using the .NET...  More
11 days ago

San Juan, PR 30-April-2017

Web Developer (.NET)
Source: Indeed
Details: ASP.NET, MVC, MS SQL Server, JQuery and Object Oriented Design concepts. Design, develop, and implement data-driven Microsoft ASP.NET web applications for EA...  More
23 days ago

Hunt Valley, MD 17-April-2017

Sr. C#.NET Developer / Lead
Source: TechPeople
Details: Experience in Web application development with ASP.NET, MVC, HTML, JavaScript, CSS, and AJAX. Sr....  More
14 days ago

Houston, TX 26-April-2017

.NET Application Developer - Lead
Source: 2rbConsulting
Details: Experience with ASP.NET MVC and Web Forms. 2rbConsulting is seeking an experienced Lead .NET Application Developer, working with a Product Development &...  More
14 days ago

Rancho Cordova, CA 26-April-2017

Houston, Texas .NET Developer
Source: Indeed
Details: Experience with .NET Framework components such as ASP.NET MVC, MSSQL, Web Services, and OOP concepts. Seeking an experienced .NET developer with a strong...  More
28 days ago

Houston, TX 13-April-2017

Senior/Lead .Net Application Developer
Source: SunTrust
Details: Senior/Lead .Net Application Developer-W428880 Description The successful candidate is a technical individual who has a passion for delivering high quality  More
18 days ago

San Diego, CA 22-April-2017

.NET Developer, Senior Level
Source: Nexient
Details: Experience with modern frameworks – MVC and bootstrap at a minimum. Strong experience in object oriented design & development, Design Patterns, Multi-threading,...  More
30+ days ago

Nashville, TN 07-April-2017

.NET/C# Software Integration Engineer
Source: BlueVolt
Details: Solid programming experience with C#, WCF, Restful services using WEB API, and ASP.NET MVC. BlueVolt is growing....  More
13 days ago

Portland, OR 27-April-2017

.NET Developer
Source: Skills Provision Ltd
Details: O ASP.NET MVC 4+. O Telerik UI for ASP.Net MVC. Are you ready for your next challenge?...  More
6 days ago

Houston, TX 04-May-2017

C# .Net Developer
Source: Indeed
Details: Location: *Modesto, CA* Duration: *1 Years* *Senior C#.Net Developer* *Face to Face Interview required* Job Summary * Under the general supervision of the  More
7 days ago

Modesto, CA 03-May-2017

C# .Net Developer
Source: Indeed
Details: Experience with multiple program languages specifically C#, ASP.NET, JavaScript, Angular, ASP.NET MVC....  More
9 days ago

Raleigh, NC 01-May-2017

The post Top 20 Entity Framework Interview Questions – MUST HAVE appeared first on Web Development Tutorial.

Must Have NodeJS Interview Questions – Part 2

0
0

This is Part-2 in series of NodeJS Interview Questions, we are trying to explore more intermediate to advanced level concepts related to NodeJS. If you landed to this NodeJS Tutorial directly, we will highly recommend to go through the previous part to understand the beginner level concepts about the technology first, otherwise you can continue reading with this NodeJS article and let us know about your  feedback at the end in comments sections.

We have tried our best to explain all related topics/concepts in detail with the help of practical examples, NodeJS source code and screenshots/diagrams wherever required. This Node.js Tutorial will also be helpful for practically preparing an interview about NodeJS technology.NodeJS Tutorial

NodeJS Interview Questions – Part 2 PDF version will be available later for download.

Getting Started NodeJS Tutorial List


Following Node.js & Related Tutorials will be helpful to practically grasp the technology.

Advanced NodeJS Interview Questions List

Explain Event Loop Architecture of Node.js?

The applications are processed in a event-loop way using the following steps:

  • When a request or task arrives, it is stored in a event queue.
  • Event queue is then replicated with respective closure, where closure is an inner functions that includes corresponding event along with it’s callback. Event loop helps to run multiple number of event concurrently even though NodeJS Architecture still running in “single-threaded” fashion.
  • Event Loop is a queue of callback functions.
  • The event loop then sends the request to worker thread from a c++ Thread pool, handled by libuv library. All I/O request is performed asynchronously by the threads in the thread pool.
  • Once the thread completes the corresponding I/O request, the associated callback is queued for processing.
  • Event loop executes the callback and return the response.Event Loop Architecture
  • Event loop itself if a single thread running in a single process. Therefore, when an event happen this can run without interruption.

Back to top

How EventEmmiter Works?

Nodejs allow to create custom event using event module and eventemmiter class.

  • Get the reference of EventEmitter class of events Module.
    var events = require('events');
  • Create an object of EventEmitter class by using the reference.
    var phoneEvent = new events.EventEmitter();
  • Subscribe to event.
    var incomingcall = function ringBell()
    {
      console.log('cring cring’);
    }
    var recievecall = function ringBell()
    {
      console.log('receive call’);
    }
    var rejecetcall = function ringBell()
    {
      console.log('reject call’);
    }
    
    phoneEvent.on('cring', incomingcall);
    Here, ‘cring’ is the first event, which has register to ‘incomingcall’ listener function. It is possible to register same event to as many as possible functions. Such as:
    phoneEvent. addListener('cring', incomingcall);
    phoneEvent.on('cring', recievecall);
    phoneEvent.on('cring', rejectcall);
  • Emit the event.
    phoneEvent.emit('cring');
  • It is possible to count number of listener to any event.
    var countListener = require('events').EventEmitter.listenerCount
       (eventEmitter, 'cring');
    console.log(countListener + " Listner(s) listening to cring'vent");
  • Remove any listener.
    phoneEvent.removeListener('cring', rejectcall);

Back to top

Explain Process Object in Node.js?

‘Process’ object is a global object, always available to Node.js application, therefore, it need not be injected using requires. This object provides the functionality in order to get control of currently running processes. Some other feature of process object are as following:

  • This object is an instance of EventEmitter.

Methods accessible from ‘process’ object:

Method Name Description
process.abort() Abort the currently running process immediately.
process.arch Returns the architecture of the currently running process.
process.argv Returns an array of argument passed at the starting of the Nodejs process.
process.argv0 Stores a read-only copy of the original value of argv[0] passed when Node.js starts.
process.channel Refers the IPC channel.
process.chdir(directory) Change the current working directory.
process.config Returns the configuration.
process.connected Return ‘true’ if the IPC channel is connected to the process.
process.cpuUsage([previousValue]) Returns user and system CPU time usage of the current process.
process.cwd() Returns the current working directory.
process.env Returns an object defining the environment.
process.emitWarning(warning[, name][, ctor]) Emit custom message.
process.execArgv Returns the set of Node.js-specific command-line options passed when the Node.js process was launched.
process.execPath Returns the absolute pathname of the executable that start the Node.js process.
process.exit([code]) Instructs to exit current process with specified code.
process.exitCode A number that define the code for exiting the process.
process.getegid() Returns the corresponding id of the process.
process.geteuid() Returns the corresponding user  id of the process.
process.getgroups() Returns an array of group id.
process.getuid() Return the id of the user.
process.hrtime([time]) returns the current high-resolution real time in a [seconds, nanoseconds] tuple Array.
process.initgroups(user, extra_group) initializes the group access list those are enlisted in /etc/group file.
process.kill(pid[, signal]) Send signal to the process identified by the pid, it may perform something other than killing the project.
process.mainModule Invoke the original main module.
process.memoryUsage() Return the memory used by the Nodejs process computed in bytes.
process.nextTick(callback[, …args]) Adds the callback to the “next tick queue”.
process.pid Return the pid of the process.
process.platform Returns the information related to operating system platform.
process.release Returns information related to current release.
process.send(message[, sendHandle[, options]][, callback]) Communicates with parent process by sending message.
process.setegid(id) sets the corresponding  group identity of the process.
process.seteuid(id) Sets the corresponding  user identity of the process.
process.setgid(id) Sets the group identity of the process.
process.setgroups(groups) Sets the supplementary group IDs for the Node.js process.
process.setuid(id) Sets the user identity of the process.
process.stderr Returns a Writable stream.
process.stdin Returns a Readable stream.
process.stdout Returns a Writable stream.
process.title Returns the current value of process.
process.umask([mask]) Return file mode creating mask..
process.uptime() Returns a string number of second for while the nodejs process is running.
process.version Returns a json object containing the version for Nodejs.
process.versions Returns a json object containing the version for Nodejs and its dependencies.

Back to top

Explain Cluster Server Object in Node.js?

Usually, a single instance of Nodejs run in a single thread, however, to enable concurrency, it is required to launch a cluster of NodeJS process. This is way to create multiple process, however they all uses the same port. Usually Node.js application run locally on localhost:3000 port. One app runs on one server using single thread on a single process. Using cluster, if the app is running on a i7 having 8 core of processor, then server will be running using 3000 port.

Create an express app by following steps describes here.

  • Create a folder called ‘helloworld’
  • Open command prompt at the new folder  and run ‘ng init’ this will create the package.json and add dependencies for express.
    {
      "name": "helloworld",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1"
      },
      "dependencies": {
        "express": "^4.10.6"
      },
      "author": "",
      "license": "ISC"
    }
  • Run ‘npm install’. This will install express and required libraries in node_modules folder.
  • Create a file called ‘index.js’ inside ‘helloworld’ folder.
    var express=require("express");
    var app=express();
    
    app.get('/',function(req,res){
     res.end("Hello world !");
    });
    
    app.listen(3000,function(){
       console.log("App is Running at PORT 3000");
    });
  •  Run ‘node index’. This will start appNode.js Application
  • From browserNode.js App Tutorial
  • Install cluster with command ‘npm install cluster’
  • Install os module ‘npm install os’.
  • Create another file cluster.js.
    var cluster = require('cluster');
    var numCPUs = require('os').cpus().length;
    
    if (cluster.isMaster) {
    
      for (var i = 0; i < numCPUs; i++) {
        cluster.fork();
      }
    
     cluster.on('online', function(worker) {
            console.log('Worker ' + worker.process.pid + ' is online');
        });
    
        cluster.on('exit', function(worker, code, signal) {
            console.log('Worker ' + worker.process.pid + ' died ');
            console.log('Starting a new worker');
            cluster.fork();
        });
    } else {
        require("./index.js");
    }

There are two types of process, if the process is Master, it is possible to copy the same process for number of CPU available in current machine. These copy processes are called worker process.  If any process is not master, they are treated as normal NodeJS program.

Now if we change the index.js as following:

var express=require("express");
var app=express();
app.get('/',function(req,res){
 res.send('process ' + process.pid + ' says hello!').end();
});

app.listen(3000,function(){
   console.log('Process ' + process.pid + " is Running at PORT 3000");
});

Now if we run the cluster it will give us following output.NodeJS App Output

Therefore, if any given time 400 users hit /login endpoint, without clustering there would be one instance of server to process 400 login request. However, with clustering now for this example, there are 8 instance of the same program, therefore, each of them will serve 50 requests.

How it Works?

  • Child/ worker process is created by triggering the child_process.fork() method. Each worker process can communicate to their parent process through IPC.
  • Master process keep listening for incoming message from worker process. Usually it follows round robin scheduling to receive any incoming message among a number of worker process.
  • Master process can also communicate directly to a particular worker process.

Back to top

This mini NodeJS course will help you learn how to design your own eCommerce website using NodeJS, Express and Kraken. NodeJS is a brilliant open-source JavaScript runtime environment that allows developers to create powerful and dynamic server-side web applications.

In this project-based course, you will build an entire Bookstore from scratch. You will be able to add, edit and delete books to the backend and customers will be able to browse, add and delete books from their cart as well as purchase it using Paypal.

NodeJS Course
Take this Course Online Now

What is NodeJS Module? Explain various modules in Node.js? E.g. Request Module | Color Module etc.

What is NodeJS Module?

Modules are developed by the community developers and published under NPM. There are a number of modules. As these modules are not Nodejs built in library, therefore, it is necessary to install these modules using npm install command.

npm install <moduleName>

  • A set of codes and file of codes are packaged in a single package and thereby the package is called the module.
  • Every module has its own scope, therefore, a number of modules running at the same time do not conflict with each other.
  • Module can be installed using following command.
    npm install <moduleName>

    In order to install a module globally

    npm install -g <moduleName>

  • Modules can be given global access.
  • Module can be updated using update command
    npm update <moduleName>

  • In order to use any module in Node.js project, it need to be imported as following:
    var module1 = require(‘<moduleName>’);

    module can also be imported from file

    var module 2 = require(‘/home/username/modules/<modulename>’);

    module can also be imported from folder

    var module 3= require(‘./directoryName’);

  • In order to publish any module, it is required to export the module as following:
    export.Square=function(a) {
    return Math.pow(a,2);
    }

Node.js Color Module:

This is one of the very popular modules for Nodejs.

Install Color Module as:

NodeJS Color Module

Node.js Request Module:

  • Install request module
    ‘npm install request’
  • Declare variable in index.js.
    ‘var req= require(‘request’)’
  • Use request module to create action.
    request('http://www.yahoo.com', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body); 
        }
    })
  • Make a GET request.
    request({
        url: ‘https://randomuser.me/api/’, 
        qs: {results: 10, time: +new Date()}, 
        method: 'GET',
        headers: { 
            'Content-Type': 'application/json'
        }
    }, function(error, response, body){
        if(error) {
            console.log(error);
        } else {
            console.log(response.statusCode, body);
        }
    });
  • Make a POST request.
    var req_options = {  
      method: 'POST',
      uri: 'https://abc.com/login',
      body: {
        username: 'xyz',
        password: ’abc’
      },
      json: true 
      }
    
    request(req_options)  
      .then(function (response) {
        // perform other operation
      })
      .catch(function (err) {
        // error handling
      })

Back to top

More NodeJS Interview Questions and Answers

What are the followings in Node.js? Karma, Jasmine, Grunt

Karma in NodeJS:

Karma is a testing framework to run JavaScript test case using jasmine test framework.

Jasmine in NodeJS:

It is a behavior driven test framework for testing JavaScript code. This is independent from any other JavaScript module.

Grunt in NodeJS:

This is a command line tool to run task. Grunt has a number of library to deploy the front end code get ready for production.

Here are the steps for building application with Grunt:

Setup Karma and Jasmine to test:

  • Install Karma by using the command.
    npm install karma --save-dev
  •  Install jasmine plugins.
    npm install karma-jasmine karma-chrome-launcher --save-dev
    Alternative is to configure in package.json, adding karma and jasmine as devdependencies as following and run npm install to run all the dependencies.
    "devDependencies": {
        "jasmine-core": "^2.2.0",
        "karma": "^0.12.31",
        "karma-chrome-launcher": "^0.1.7",
        "karma-jasmine": "^0.3.5"
      }
  • Install command line for karma.
    npm install -g karma-cli
  • Run karma from command line by typing ‘karma start’. Usually karma server will be launched at http://localhost:9876/NodeJS Karma Tutorial
    Alternatively , using package.json and using configuration from karma.conf.js file.
    "scripts": {
    "test": "karma start karma.conf.js"
      }
  • The next step is to config karma.
    module.exports = function (config) {
      config.set({
        basePath: '',
        frameworks: ['jasmine'], // List of test frameworks. Typically, ['jasmine'], ['mocha'] or ['qunit']
        plugins: [
          require('karma-jasmine'),
          require('karma-chrome-launcher'),
          require('karma-remap-istanbul')
              ],
        files: [
          { pattern: './src/test.js', watched: false } //List of files/patterns to load in the browser.
        ],
        port: 9876,
        colors: true, //Enable or disable colors in the output (reporters and logs).
        logLevel: config.LOG_INFO,
        autoWatch: true, //Enable or disable executing the tests whenever one of  these files changes.
        browsers: ['Chrome'],
        singleRun: false
      });};

Using Grunt for Deployment:

  • Install grunt-express plugin for express web-server tasks via Grunt.
    npm install grunt-express-server --save-dev
  • Create ‘Gruntfile.js’.
  • It is possible to describe different server for deployment in Gruntfile.js.
    grunt.initConfig({
      express: {
        options: {
        },
        dev: {
          options: {
            script: 'path/to/dev/server.js'
          }
        },
        prod: {
          options: {
            script: 'path/to/prod/server.js',
            node_env: 'production'
          }
        },
        test: {
          options: {
            script: 'path/to/test/server.js'
          }
        }
      }
    });
  • Describe the options inside the options tag in Grunt config.
    express: {
        options: {
        },
  • Define the task and register.
    grunt.registerTask('rebuild', ['clean', 'browserify:scripts', 'stylus', 'copy:images']);
    grunt.registerTask('dev', ['rebuild', 'express', 'watch']);
  • Now if we run express:dev it will start the server on dev environment

Back to top

How we can create HTTPS Server with Node.js?

  • Install connect module.
    npm install connect
  • Create a middleware module, to print the message send as the parameter of the request.
    function printmessage(message){
    	return function(req, res){ 
    	res.end(message);
     };
    }
    module.export = printmessage;
  • Create the server app.
    var connect = require('connect');
    var printmessage = require('./printmessage');
    var app = connect.createserver(
    			printmessage('Hello world!!!!')
    		);
    app.listen(8080);
  • Run the server with command ‘node index’
  • From http://localhost:8080/ it will shows the message on the web page.

There are several ways to create HTTP request:

  1. Using HTTP Module
  2. Using Express App

Using HTTP Module:

  • Install ‘http’ module.
    npm install –save http
  • Create a method for a ‘GET’ request.
    var http = require('http');
    
    function getrandomepeople (callback) {
    var req_options={
            host: ' https://randomuser.me/,
            path: '/api?results=90'
        };
        return http.get(req_options, function(response) {
            // Continuously update stream with data
            var data = '';
            response.on('data', function(nd) {
                data += nd;
            });
            response.on('end', function() {
    
                var jsonObject = JSON.parse(data);
                callback({
                    results: jsonObject.results,
                    info: jsonObject.info
                });
            });
        });
    
    };
  • Create a method for POST request.
    var http = require('http');
    
    function PostData(callback) {
      // Build the post string from an object
      var data = <any Json object>
    
        var req_options = {
          host: 'https://randomuser.me/,
          port: '810',
          path: '/generate',
          method: 'POST',
          headers: {
              'Content-Type': 'application/json',
              'Content-Length': Buffer.byteLength(post_data)
          }
      };
    
      // Set up the request
      var post_request = http.request(req_options, function(response) {
          response.setEncoding('utf8');
          response.on('data', function (nd) {
              console.log('Response: ' + nd);
          });
      });
    
    //write the data
      post_request.write(post_data);
      post_request.end();
    
    }

Using Express App:

  • Create a file called route.js.
    module.exports = {
        '/alldb': {
            get: {
                controller: 'DBController',
                method: 'getAllDB',
                public: true
            }
        },
        '/database/:dbName/doc/:docId': {
            get: {
                controller: 'DBController',
                method: 'getDocument',
                public: true
            },
            put: {
                controller: 'DBController',
                method: 'persistDocument',
                public: true
            },
             'delete': {
                controller: 'DBController',
                method: 'deleteDocument',
                public: true
            }
        },
        '/search': {
            get: {
                controller: 'DBController',
                method: 'searchResult',
                public: true
            }
        }
    };
    This file will have the list of endpoints.
  • As each of the methods are described in a controller called DBController, therefore create a file called DBController.js.
    /**
     * This controller exposes REST actions for managing Games.
     * * @version 1.0
     */
    'use strict';
    
    var async = require('async');
    var DBService = require('../services/DBService');
    var helper = require('../helpers/helper.js');
    
    /**
     * List all Dbs.
     * @param {Object} req the request
     * @param {Object} res the response
     * @param {Function} next the next middleware
     */
    function getAllDB(req, res, next) {
        async.waterfall([
    	function(cb) {
    	    DBService.dblist(cb);
    	},
    	function(result) {
    	    res.json(helper.buildResponse(result));
    	}], function(err) {
    	    if (err) {
    		return next(err);
    	    }
    	});
    }
    
    /**
     * List a documet
     * @param {Object} req the request
     * @param {Object} res the response
     * @param {Function} next the next middleware
     */
    function getDocument(req, res, next) {
         var dbName = req.params.dbName;
         var docId = req.params.docId;
        async.waterfall([
    	function(cb) {
    	    DBService.getDoc(dbName,docId,cb);
    	},
    	function(result) {
    	    res.json(helper.buildResponse(result));
    	}], function(err) {
    	    if (err) {
    		return next(err);
    	    }
    	});
    }
    
    /**
     * save a documet
     * @param {Object} req the request
     * @param {Object} res the response
     * @param {Function} next the next middleware
     */
    function persistDocument(req, res, next) {
         var dbName = req.params.dbName;
         var docId = req.params.docId;
        async.waterfall([
    	function(cb) {
    	    DBService.persistDocument(dbName,docId,cb);
    	},
    	function(result) {
    	    res.json(helper.buildResponse(result));
    	}], function(err) {
    	    if (err) {
    		return next(err);
    	    }
    	});
    }
    
    /**
     * delete a documet
     * @param {Object} req the request
     * @param {Object} res the response
     * @param {Function} next the next middleware
     */
    function deleteDocument(req, res, next) {
         var dbName = req.params.dbName;
         var docId = req.params.docId;
        async.waterfall([
    	function(cb) {
    	    DBService.deleteDocument(dbName,docId,cb);
    	},
    	function(result) {
    	    res.json(helper.buildResponse(result));
    	}], function(err) {
    	    if (err) {
    		return next(err);
    	    }
    	});
    }
    
    
    module.exports = {
        getAllDB: getAllDB,
        getDocument: getDocument,
        persistDocument: persistDocument,
        deleteDocument: deleteDocument
    };
  • Now from browser, if we call any endpoint defined on route.js and corresponding http request will be executed.

Back to top

How to achieve Concurrency in Node.js?

Eventloop is a single thread running in single process. However there are several ways to achieve concurrency in Nodejs as following:

Asynchronous Programming:

  • Developing application using Asynchronous Programming. async module is very helpful to perform this.
    var async = require('async');
    /**
     * List all Dbs.
     * @param {Object} req the request
     * @param {Object} res the response
     * @param {Function} next the next middleware
     */
    function getAllDB(req, res, next) {
        async.waterfall([
    	function(cb) {
    	    DBService.dblist(cb);
    	},
    	function(result) {
    	    res.json(helper.buildResponse(result));
    	}], function(err) {
    	    if (err) {
    		return next(err);
    	    }
    	});
    }
  • An asynchronous function invokes a callback, here cb in the above example which is a function passed as the last argument, this function would be called as the next in the sequence in order to continue the program once the current one has been finished.
  • The threadpool can provides a fixed number of thread. For large scale application where so many operations need to be executed concurrently, the thread pool should have larger number of threads and for small application it is ok if the thread pool has only few threads. It is important to define the number of thread in the thread pool in order to achieve concurrency.
  • Although there is single thread, however multiple process will enable concurrency.

Launching Cluster:

By creating a small network of multiple processes those share main server ports; The details of clustering has been descried above NodeJS Cluster Server Object Interview Questions.

Back to top

What is web scrapping?

Web scrapping is the technology to crawl web page and retrieve information from the wed page. The steps require to extract information using web scrapping are as following

  • We load the page
  • Parse the HTML result
  • Extract the needed data

And the technologies those are required for web scrapping are as following

  • NodeJS
  • ExpressJS: A web framework.
  • Request: make Http Request
  • Cheerio: Implementation of core jQuery functionality for the server. This helps to get value for DOM element
  1. Install express
    npm install express
  2. Install request
    npm install request
  3. Install Cheerio
    npm install cherrio
    In index.js , load express, request and cheerio module
    var express = require('express');
    var request = require('request');
    var cheerio = require('cheerio ');
  4. Initialize  express app
    var app = express();
  5. Start  server
    app.listen(8080);
  6. Create an endpoint go through the IMDB web page or the movie ‘Moana’.
    app.get('/scrapeweb', function(req, res){
        url = 'http://www.imdb.com/title/tt3521164/';
       request(url, function(error, response, html){
            if(!error){
                // load cherrio to parse the target html page
                var $ = cheerio.load(html);
                // read only the target DOM element 
                 var title, release, rating;
                var json = { title : "", release : "", rating : ""};
            }
        })
    });

Back to top

How to handle JSON files in Node.js?

These are the following step to handle json file:

Reading JSON File:

  • Import fs module.
    var fs =require('fs');
  • Read file synchronously.
    var jsoncontent = fs.readFileSync('profile.json');
  • Parse the read content to json object.
    var profile = JSON.parse(jsoncontent );
  • Get any property of the json file.
    console.log("user Name:", profile.username );

Writing JSON File:

fs.writeFile(‘profile.json’, JSON.stringify(profile, null, 4), function(err) {
    if(err) {
      console.log(err);
    } else {
      console.log("Profile is saved to profile.json");
    }
});

Alternatively, it is possible to read json file using require. File extension is optional for this command.

var profile = require('./profile’);

Back to top

Twitter Bootstrap has become the most widely used framework for quickly building responsive websites, and they’re currently launching Bootstrap 4 to the public. This new version of Bootstrap comes with a ton of new features to help you build even better responsive websites. More about this Course Here.
Responsive Design with Bootstrap

This Node.js Interview Questions Part-2 in series of Node.js Tutorial completes all important concepts related to this technology. We will come up with more related technology tutorials to elaborate other related web development concepts. If you feel something really important that is missing, you can contribute by adding your valuable suggestions in comments section.

Top Technical Interview Questions and Answers Series:

The post Must Have NodeJS Interview Questions – Part 2 appeared first on Web Development Tutorial.

Top 20 MongoDB Interview Questions

0
0

In order to build a MEAN-based web application, MongoDB plays the key role along with AngularJS, NodeJS and Express. In this MongoDB Tutorial, our focus is to start learning MongoDB from beginning. This article can also be taken as Part-1 in Series of MongoDB Interview Questions with practical and detailed answers. We will start will very basic questions about MongoDB including What it is? How to create a NoSql database using MongoDB and then moving to more advanced topics.MongoDB Interview Questions

Getting Started MEAN Stack Tutorial Series

We already have covered other components of Full Stack JavaScript by cover the followings:


MongoDB Interview Questions Tutorial – From Beginner to Professional

What is MongoDB, explain MongoDB as Nosql database in detail and how it is different from relational database?

MongoDB is cross platform document based database. It is a NoSql database and very different from traditional relational databases like Oracle, MS SQL, MySQL etc. MongoDB provides high availability, high performance and easy scalability. Easy scalability means it is very easy to scale MongoDB database in comparison of relational databases.

MongoDb works on the concept of document and collections. We will go through each and dig down in detail. Lets first quickly understand what NoSql databases is?

What is NoSql database?

NoSql referred as non-sql databases that enables us to store and retrieve data in non-tabular format. When we say non-tabular format then we want to say there will no tabular database like relational database. So the data will be present in non-tabular formats.

Now lets understand what document and collection is, with respect to MongoDB, which are backbone of this database.

Document:

Document in MongoDb is a set of key value pairs. Each document has schema associated with it. These schema are dynamic in nature. MongoDb stores documents as BSON data, that stands for Binary representation of JSON data. BSON is binary serialization format that is used to store JSON data. As we discussed above MongoDb documents are key-value pair set and have the following structure.

{
    Key1: value1,
    Key2: value2,
    Key3: value3,
    Key4: value4,
    Key5: value5
    ...
    ...
    keyN: valueN
}

Value can be any of the datatype that BSON supports. BSON supports number of datatypes.

Collection:

In MongoDb collections are used to store documents. Collections can be taken as tables in relational databases.

If we compare MongoDb with relational databases, then Table of relational database is called Collection in MongoDb, Row of relational database is document in MongoDb, Column is called field here and joins are referred as embedded documents.

Below is the simple example of a document:

{
    _id: ObjectId(76dede33htfeed4)
    employeId: 299377,
    employeName: "Jerry",
    address: "Street3, NY",
    technologyKnown: ['java', 'python'],
    salary: 108770,
    education: [
        {
            degree:"MCA", 
            dateCompleted: new Date(2009,2,10,1,11)
        },
        {
            degree:"BSC", 
            dateCompleted: new Date(2006,2,10,1,11)
        }
    ]
}

In the example above we have created a simple document, that contains information about a employee.

_id is the identity of document, it is basically a hexadecimal value, that ensures uniqueness of a document. As we can see employeeId is type of int, address is String, technlogyKnown is array of Strings. In the education field, there is date field. There are verify of datatype that MongoDb supports.

Although there are few restrictions with key or field names:

  • Field names cannot be null.
  • Field names cannot contain dot (.)
  • Field names cannot start with dollar sign($).

_id is reserved for primary key in MongoDb.

Back to top

What are key advantages of MongoDB?

Key Advantages of MongoDB:

Following are  the  key advantages of using MongoDB i.e. a NoSQL database:

  • Removal of Complex Joins:
    unlike relational databases where tables are referentially connected, and to retrieve data, we need to build a complex query using joins. To write such complex queries one need to have a very good command on db. In MongoDb you need not to write such complex queries, all you need to do is to design a good schema that will contain these documents
  • Easy to scale:
    MongoDb enables us to horizontal scale the database. For this purpose there is technique called sharding is used.
  • Clear structure of object:
    In MongoDb if there is good schema defined, there will be a very clear structure of object and one can easily identity the collection and document structure.
  • Failover:
    Failover is automatically handled, that means , in a cluster if a node goes down which is primary, secondary node automatically comes up.

Back to top

Learn the #1 Resource to Become a MEAN Stack Developer

Plus, Quick and Easy way to develop your First Angular 2/ Angular 4 Real-world Application with a NodeJS Backend.
  • Learn MEAN Stack Development
  • How AngularJS interacts with BackEnd
  • Use MongoDB with Mongoose
  • Using ExpressJS as NodeJS Framework
  • Front End Optimistic updation

Learn More Now…Click Here

Explain with steps how to configure MongoDB in details, attach code snippet and diagram whereever applicable?

To configure MongoDb on our local machine or on some remote machine, first we need to download the extract of MongoDb from MongoDb official website (https://www.mongodb.com/download-center).

Based on the operations system, we need to download the extract or installation file. Make sure you are downloading the latest version of MongoDb.

One you have downloaded the extract from web. Now we need to install and configure it. Here we will be talking about installation and configuration on Windows operating system. First we need to install the extract file that is downloaded from MongoDb official site.

First we need to create two folders data and under data we need to create db folder. Following will be commands for the same.

Here I am creating these two folders in C drive.MongoDB Tutorial

Once we have created these two directories, we need to navigate to bin folder of mongodb insallation directory. After that we need to run the command as below :

mongod.exe –dbpath “C:\data\db”

MongoDB Installation TutorialIf every things goes fine then, console will show waiting for connections, which indicates that mongodb has been installed and configured successfully.MongoDB Configuration

Now to run MongoDb, open console in other console. And run mongo.exe command.MongoDB Commands

In the snap above, we have connected to mongodb and created a test record and executed a find command which ensures that mongodb has been installed and executed successfully. These find and save commands will be covered in next questions.

Back to top

Explain how to define schema in MongoDB with example, how these schemas are different with RDBMS schema, explain with example?

Data in MongoDb is stored in form of key , value pairs. And a set of these data is called document in terms of MongoDb. Each document has a flexible schema. Documents don’t need to have the same set of fields, structure. MongoDb provides such flexibility.

While designing mongodb schema , there are few things that we need to keep in mind.

  • Objects that are intended to use together, should be kept in a document. If not then its better to separate these objects in different documents.
  • Schema should be optimized for the queries or use cases that are most frequently used.
  • Joins can be used but make sure to use joins while writing data on data base not while reading data from database.
  • Schema should be designed particularly on the requirement and should be flexible.

Lets try to understand it with an example and we will compare the schema of MongoDb with RDBMS schema.

Lets suppose we are designing a online shopping web application. Which have the following requirements:

  • There will be multiple items with some tags.
  • Each item will have unique name and description.
  • Each item will have information about seller, name and id.
  • Each item will have then number of comments given by users with likes and dislikes
  • On each item can have multiple comments or no comments.

Lets see how RDBMS schema will look like:MongoDB Schema Example

As we can see, as per our requirement, there will three tables, which will have relation to each other. There will be an item table with some fields, which will have connected with tags table. Tags table will have referential relation with item table, Same goes for comments table, which will also have referential relation with item table.

Now lets try to achieve the same with MongoDb. Lets design schema for the same in MongoDb. MongoDb schema will have a well defined collection, which will adhere to the requirement. Below is the schema for the same.MongoDB Schema Tutorial

Now if we compare both the schemas, we can see in relational database we need to create three different tables with referential relation, where as in MongoDb the same can be achieved by just a well defined collection.

Back to top

Explain how to create database in MongoDB?

To create database in MongoDb, ‘use’ command is used. This command is used to create database in MongoDb. It will create database if doesnot exists if exists it will return the existing database name. In MongoDb the default database is ‘test’. If we don’t create any database the collections will be stored in the default test database.

Syntax of this command is as follows:

use <DATABASE_NAME>

Lets try to understand this command with example :

Suppose we need to create database with name BookStore. Syntax for the same will be:Create MongoDB DatabaseLets say we want to check the list of database, we will use the show dbs command. Below is the syntax for the same.MongoDB Database Tutorial

Wondering ! why our newly created database is not in the list. The answer is the database should have at least one document stored. Once our db will have records or documents, it will be displayed in the list.

Lets create a record in db and try to check the same with show dbs command.Show DBS Command

Here we have created a document and stored a record in this. Now if we check with the same command , as you can see our newly created database BookStoreDb is top on the list.

If you want to  check on which database you are currently on, db command will be used, below is the syntex:BookStoreDB in MongoDB

Back to top

What are collections in MongoDB, explain with example?

Collections in MongoDb:

Collections in MongoDb are similar to tables in relational databases. Collections contains the documents in MongoDB. These documents may or may not be in the same structure.

To create collections in MongoDb createCollection is used. Syntex to create collection in MongoDb is :

db.createCollection(name, options)

This method takes two parameters, name and options. Name is implicit that is name of collection that is being created. Options is the optional parameter and of document type. Which will have configuration related to document.

Below are the configuration options for collection:

  • autoIndexID, which is Boolean type of field, optional parameter, true means index should be creted on the _id. Default value is false.
  • max , number type of field, optional parameter, indicates max number of documents allowed in the collection.
  • capped , Boolean type of field, optional parameter, if true creates a capped collection.
  • size , number type of field, indicates the size of capped collection.

Lets try to understand with creating a collection:Creating Collections in MongoDB

Here we have created a collection with ComputerProgramming name.

Now lets check the created collection. To list the collections in MongoDb, the following command will be used:

show collections

Lets try it:Show Collections

As we can see it has the list of collections and our newly created collection(ComputerProgramming) as well.

Now lets create collection with the optional fields:MongoDB Collections Tutorial

As we can see, MongoDb has created collection with the options provided. Lets try to list collections now, it should both the collections that we have created.MongoDB Collections List

In MongoDb, we don’t need to explicitly create collections. MongoDb automatically creates the collections once we insert document. Lets try to create  a collection not with createCollection command, but directly inserting records.Show Collections in MongoDB

As you can see now, we have directly inserted document in ScienceBooks collection, which was not present. MongoDb automatically created ScienceBooks document and inserted records in it. In show collection command now it has the collection, ScienceBooks. It is all about collection and database in MongoDb.

Back to top

Learn Professional Web Development in AngularJS while building 10 unique Web Apps.
77 lectures, 14.5 Hours Video, All Levels
  • Your First Angular Website
  • Web Template Store
  • myContacts App
  • ngSocial Facebook App
  • Job Directory
  • KnowledgeBase
  • User Authentication App
  • Instagram Gallery
  • PubNub Chat
  • AutoFind

And also we will find Quiz at the end of each application to verify the skill improvement.

Intermediate to Advanced MongoDB Interview Questions Tutorial

How to create backup and restore the MongoDB database? Explain with example?

Backup is basically to create a dump of existing database, that can be restored as and when required. As in relational database, MongoDB also provides the functionality to create dump of database and use it dump when required, with restoring functionality.

Creating Backup with MongoDB:

In order to create backup of existing database in MongoDB, MongoDB provides mongodump command. Using this command we can create dump of database. This command will create the entire dump of your database in the dump directory.

mongodump

There are few options available with this command, that can be used as needed. Following are the options available with this command:

mongodump  --host <host-name> --port <portnumber>
This command will create the db dump on the given mongodb instance.
For Example:
mongodump –host bookstore.com –port 34889

mongodump --dbpath <path_of_db_that_needs_to_be_backedup> --out <output_directory_for_backup>
This command will create db dump of specified database on the specified output directory.
For Example:
mongodump --dbpath /data/db/ --out ../backup/

mongodump --collection <collection_name> --db <database_name>
This command will create dump of specified collection of specified database.
For Example:
Mongodump --collection OrganicChemistry --db ScienceBooks

Now lets create a backup of db. For this we need to traverse to bin directory of Mongodb installation. Once we are on the bin directory on command prompt, run ‘mongodump’ command. This command will create a dump directory in bin directory of MongoDB. And it will keep all the backup in this folder. Lets try to run the command:MongoDB Tutorial Taking Dump

As we can see, it has created dump of our database successfully. Let’s traverse through the folder structure and try to see dump folder contents:MongoDB Dump Folder Structure

So this will be the folder structure of dump folder. It has created the dump and as we have created BookStoreDB, we can see the dump of that db as well.

Restore Backup with MongoDB:

Similarly to restore the backup, MongoDb comes up the mongorestore command, this command will restore the backup created.

mongorestore

To run this command we need to traverse to bin directory from command prompt and once we are on bin directory, we need to run this command. Lets try to run this command and see:MongoDB Restore Tutorial

As we can see, our created backup has been restored with this command.

This is all about backup and restore database in MongoDb.

Back to top

What are CRUD operations and how these crud operations are performed in MongoDB? Implment a proper example with PHP to connect with MongoDB and perform all CRUD Operations.

CRUD operations in database terms stands for Create, Retrieved, Update, Delete. All databases irrespective of Sql or Non sql have these functions in place. We will go through one by one with example in MongoDB and PHP.

MongoDB and PHP Example:

Like relational database connection, first we need driver to connect. For this we need to download driver from official site. Once we are done with download of driver, we need to put the dll file that is php_mongo.dll in ext directory. After adding the file to ext directory in php.ini file we need to add a line that will have a reference to this dll file.

extension = php_mongo.dll

Once we are done with this, we are set to go with our php code that will create database connection and perform these operations. Lets start with connecting to db and creating a collection:

<?php
   $connection = new MongoClient();
   $database = $connection->BookStore;
   $collection = $db->createCollection("ScienceBooks");
   echo "Collection ScienceBooks created succsessfully, on BookStore database";
?>

The code above will create connection to MongoDb database instance. It will take the database which is BookStore in our case. Once we have selected BookStore database, we are good to go with creating a collection. createCollection() function will create a collection in our case we are taking collection as ScienceBooks. If everything goes fine, we will able to see the below on console.MongoDB and PHP Tutorial

Once our collection is created, we are good to go with performing CRUD operations.

Lets start with C, that is create a record. To create a record, insert() method is used in MongoDb, that takes document as argument, which contains the data that needs to be inserted.

Lets suppose in our bookstore, we need to create records for ScienceBooks, that will have BookName, BookAuthor, ISBN fields. Now are already created collection for ScienceBooks, all we need to do is to create a records underneath it. Below is the example to achieve the same.

<?php
   $connection = new MongoClient();
   $database = $connection->BookStore;
   $collection = $db->ScienceBooks;

   $record = array(
      "BookName" => "Organic Chemistry",
      "BookAuthor" => "James",
      "ISBN" => "45387644"
   );

   $collection->insert($record);

   echo "Created a record in BookStore Db.";

?>

Lets try to understand the above code, we have already created a collection. Now we need to create a record underneath it, what we have done is we have created a record with the fields, for example purpose and make code readable I have hardcoded the values, which will never be in real world scenario, values will be dynamic and not static. We can add as many records in the array as we want. Once our array is ready with the records, all we need to do is to pass it to insert method. If everything goes fine, the below message will be displayed on our console.CRUD Operations with MongoDB

Now lets come to R, that is for read operations in CRUD. Lets try to find out the record that we have just created. To read or in other words to find document in MongoDb term, find() method is used. Lets simulate from code and try to retrieve record from BookStore database.

<?php
   $connection = new MongoClient();
   $database = $connection->BookStore;
   $collection = $db->ScienceBooks;

   $records = $collection->find();

   foreach ($records as $record) {
      echo "BookAuthor :: " . $record[“BookAuthor"] . "\n";
   }
?>

In the above code fragment what we have done is, we have fetched records from ScienceBooks collection, and print BookAuthor. So basically find method will return me list of all records, once I get list of records, we need to traverse through is to get records and print the required value from key associated with it. Like in the code above we have printed book author, which was stored with BookAuthor key.

In crud operations, U stands for updating records in the database. In MongoDb, updations on a record is done though update() method. Just now we have created a records in BookStore database and in ScienceBooks collection. Now we need to updated it through and lets suppose we need to update ISBN number which was by mistake entered incorrect. Below is the code for the same:

<?php
   $connection = new MongoClient();
   $database = $connection->BookStore;
   $collection = $db->ScienceBooks;

   $collection->update(array("ISBN"=>"45387644"),
      array('$set'=>array("ISBN"=>"45387984")));

   $records = $collection->find();

   foreach ($records as $record) {
      echo "ISBN :: " . $record[ISBN"] . "\n";
   }

?>

In the example above, we have just updated the ISBN number that was stored incorrect, we have updated to correct one and finally printed the updated entry. After successful run of the above code fragment we will get ISBN number as 45387984.

Finally lets come to D, that is delete operation in CRUD. To delete a record or in MongoDb terms, to delete a document from database, remove() method is used. Lets try to remove the document with ISBN key as 45387984, which we have just updated:

<?php
   $connection = new MongoClient();
   $database = $connection->BookStore;
   $collection = $db->ScienceBooks;

   $collection->remove(array("ISBN"=>"45387984"));

?>

In the code fragment above we have deleted a record with ISBN key as 45387984. Now if we add the fetch code here and try to traverse over it, it will print nothing. Since the document is no more in the database.

Back to top

What are indexes with respect to a database, how indexing is performed in MongoDB, explain with example?

Indexes are basically a special kind of data structure in database term, which helps to optimize the query performance. Basically while searching in MongoDB , in a normal search, let suppose you have millions of documents in a collection, then for a particular document search, MongoDB have to search through each and every document in the collection which is time taking. While having indexes in place, MongoDB will limit the search with help of these indexes.

In principle Indexes stores the value of a specific field or a set of fields ordered by the value of the field. Since the data is partial, it becomes easier to read this data.

Creating Indexes in MongoDb:

To create index in MongoDb, createIndex method is used. Below is the syntax to create index in MongoDB.

db.<collection_name>.createIndex(<key>:<ascending parameter>)

Collection name will the name of collection. Key will the key on which index needs to be created, next parameter indicates that the key on which index to be created, it’s values should be in ascending or descending order. 1 indicates that values will be in ascending order, whereas -1 indicates that values will be descending order.

Lets take an example, Suppose we have a BookStore database which have collection as ScienceBooks. Document in this collection looks as:

{
	BookName : <Some Book Name>
	BookAuthor: <Some Book Author>
	ISBN: <ISBN>
}

Lets assume we need to create index on BookName field. Below will be code for the same:

db.BookStore.createIndex({BookName:1});

The above code will create a index on BookName field and the values will be in sorted in ascending order.

Indexes can be created on more than one fields, that mean, if we want to add other keys in index, we can and the index will be created on both key fields. Lets try to run the command and create the index:MongoDB Indexes Tutorial

Lets try to understand the output now :

  • numIndexesBefore indicates that how many indexes are present before this command is executed.
  • numIndexesAfter indicates that how many indexes are present after this command is executed.
  • ok represents that the operation was successful and indexes are successfully created in database.

Lets say we want to know how many indexes are there in databases and on what keys they are, getIndexes() command is used. Below is the syntax for the same:

db.<collection_name>.getIndexes()

Lets try to run the command and try to get the list of indexes present in our ScienceBooks collection:MongoDB Indexes Interview Questions

As we can see there are two indexes displayed in the output, one is on _id field and other is on OrganicChemistry field. ‘1’ , as we have discussed, indicates that field values are sorted in ascending order.

Now lets suppose, I want to delete an index from my database. There are basically two methods for dropping indexes from MongoDb. One is to delete an individual index and other is delete all indexes from database.

To drop a particular index, dropIndex() method is used, which takes key as parameter. Below is the syntax for the same:

db.<collection_name>.dropIndex({<Key_Name>:<Order>})

Drop Indexes from MongoDB:

To drop all indexes from database, dropIndexes() method is used. That will drop all the indexes present on collection.

Lets try to run and delete the index that we just created on OrganicChemistry key field:Drop Indexes MongoDB

In output we got nIndexesWas , which indicates that how many indexes were present before execution of this command, where as ok, indicates that the command run was successful.

This is all about creating. Finding and dropping indexes from database.

Back to top

What is projection with respect to MongoDB, how sorting is performed in MongoDB, explain with example?

Whenever we try to find some data from MongoDb, find() method is being used. This method will return me the documents of collection on which this is invoked. Now I can have the where clause as well in my MongoDb query so I can limit the output. Consider a scenerio where I want to retrieve particular fields of document, how to do so?

Lets dig more into it, for an example let say in our bookstore database, from ScienceBooks collection I want to find books with Author James. Whenever I will execute the find method MongoDb will return me the all the documents in the ScienceBooks collection in which Author is James. Now lets suppose I just want ISBN number of the books whose author is James. In order to achieve this there is a concept in MongoDb that is used and called Projection. Below is the syntax for the same:

db.<collection_name>.find({},{<Key_Name>:<Flag to display>})

In the command above, KeyName will be key whose corresponding fields we need to display. Flag to display takes 1 or 0 as input. 1 indicates that the corrospoinding values will be displayed where as 0 indicates that the corresponding values will not been displayed.

Lets try to simulate the same with example:MongoDB Projection TutorialAs we can see, the output of find command displayed all records of ScienceBooks collection. Now I want to have projection in place and want to see only name and not _id. Lets see how we can achieve this:MongoDB Projection Interview Questions

As we can see in the output, only name is in the output and not _id. And why it is, because if you see the find method, we have used display parameter ‘1’ with name and ‘0’ with _id.

This way we can use projection in our code to find the results which we want.

Back to top

This mini NodeJS course will help you learn how to design your own eCommerce website using NodeJS, Express and Kraken. NodeJS is a brilliant open-source JavaScript runtime environment that allows developers to create powerful and dynamic server-side web applications.

In this project-based course, you will build an entire Bookstore from scratch. You will be able to add, edit and delete books to the backend and customers will be able to browse, add and delete books from their cart as well as purchase it using Paypal.

NodeJS Course
Take this Course Online Now

So far, we have covered beginners to intermediate level MongoDB Interview Questions in this Series. Next part in this series contains more advanced MongoDB FAQs/Interview Questions with detailed examples and source code. Keep in touch 🙂

Top Technical Interview Questions and Answers Series:

The post Top 20 MongoDB Interview Questions appeared first on Web Development Tutorial.

Advanced MongoDB Interview Questions

0
0

This MongoDB Tutorial is Part 2 in series of MongoDB Interview Questions. In this technical interview questions part, we will learn about more advanced topics related to MongoDB as NoSQL database. If you haven’t gone through the previous part, we will highly recommend to go through the previous one first and then move to these advanced Interview questions or topics on MongoDB. MongoDB Interview Questions

Getting Started MEAN Stack Tutorial Series

We already have covered other components of Full Stack JavaScript by cover the followings:

MongoDB Tutorial PDF version will be available later for download.


MongoDB Interview Questions Tutorial – From Beginner to Professional

What is difference between Replication and Sharding? Can we achieve these two with MongoDB?

Replication:

Replication as the name suggests, is the process of synchronizing data on multiple servers. In other words the copy of data will be maintained on different servers. Replication gives us the surety that the data is available on more then one server. This increases the availability of data, since data will be available on more then one server. It helps us to fight against data loss since in case of fail-over of server data will be available on other servers.

With replication in place there will be no data loss, also the availability of data will be 24/7, we don’t need to worry about downtime since there are replicas and we can use any of the server to read. Data will be read scalable, that means since there are more than more copies of same data, app can use any server instance to read.

Replication with MongoDB:

In mongodb replication is achived by replica sets. A replica set is a group of mongodb instances that have the same data. In replica set one node is primary node that receives  all data and primary node then replicates the data to secondary nodes. There can be only one primary node in replica set.

A replica set is a group of two or more nodes, within which there will be one primary node and other nodes will be secondary nodes. Data is typically replicated from primary node to secondary nodes. At the time of failover a new primary node is automatically selected and connection is established to the new primary node.Replication in MongoDB

The above diagram demonstrates how replication is performed in MongoDB.

Lets see how replica sets are created?, below is the syntax for the same:

mongod.exe  --dbpath “c:\data\db” –replset “instance_name”

We need to shutdown the mongodb instance first and then again execute this command with the replica set name. –replset is the command flag that is need to start mongodb with replicaset.

Once server is started, from mongodb client we need to fire a command that is rs.intiate() to initiate a new replicaset.

Sharding:

Sharding is the concept of splitting data across multiple machines. It basically splites data among smaller datasets and stores across machines. At times querying against huge data set needs a very high cpu utilization. To tackle this situation Mongodb comes up to a concept of sharding, which actually splits the data across multiple machines. This can be a large collection of shards but logically all shards works a collection.

Components:

Components of a shard typically include the following:

  • Shard: Shard is a mongodb instance which holds the subset of data.
  • Config server: Config server is also a mongodb instance which holds information about the mongodb instances which holds shared data.
  • Router: Again a mongodb instance which is responsible for directing the commands sent by server.

This is all about Replication and Sharding in MongoDB.

Back to top

In RDBMS there are functions available for min, max, count etc. for aggregation, are there any such functions available in MongoDB to achieve aggregation, explain each aggregation function with example?

Aggregation is the concept of processing data records and return aggregated result. Like RDBMS aggregation is possible as well in MongoDb as well. Ofcoures here we will not be using select count(*) type of syntaxes but the same will be achieved by functions available in MongoDb. Aggregation group multiple records/documents from a collection and perform operation on these records and return a computed result. In MongoDb aggregate()  method is used to perform aggregation. Below is the syntax for the same:

db.<collection_name>.aggregate(<aggregate_function>)

Lets add some records in the collection ScienceBooks, with following schema:

{
	BookName : <BookName>
	Category : <Book_Category>
	Price : <Book Price>
}

To demonstrate this, we have created a records file with some data and imported to database. Below is the content of the file:

{"BookName" : "HeadFirstJava", "Category" : "ComputerScience", "Price": "100" }
{"BookName" : "HeadFirstDesignPattern", "Category" : "ComputerScience", "Price": "130" }
{"BookName" : "SpringInAction", "Category" : "ComputerScience", "Price": "400" }
{"BookName" : "OrganicChemistry", "Category" : "Chemistry", "Price": "110" }
{"BookName" : "PhysicalChemistry", "Category" : "Chemistry", "Price": "190" }
{"BookName" : "InorganicChemistry", "Category" : "Chemistry", "Price": "70" }

Lets import this file now and see the output:Sharding in MongoDB

The code above demonstrates the import and find from books collection:

Count():

Now our books collection which is in BookStoreDB has few records , with which we can play around through aggregation :

Lets suppose we want to find how many books are in Chemistry Category and how many in ComputerScience category, similar to select Category, count(*) from books group by Category;Aggregation Function in MongoDB

min() :

Now lets suppose we want to get the minimum price for each category, below is the code for the same:

db.books.aggregate(
        [
                {$group : 
                    {
                        _id : "$Category", min_price : {$min : "$Price"}
                    }
                }
        ]
);

Executing this code will result in the minimum price of book for both the categories.

max():

Similiarly suppose we want to get the maximum price for each category, below is the code for the same:

db.books.aggregate(
        [
                {$group : 
                    {
                        _id : "$Category", min_price : {$max : "$Price"}
                    }
                }
        ]
);

Executing this code will result in the maximum price of book for both the categories.

sum():

Now if we want to have the sum of price of all books available in our book store, below will be the code for the same:

db.books.aggregate(
        [
                {$group : 
                    {
                        _id : "$Category", min_price : {$sum : "$Price"}
                    }
                }
        ]
);

These all the basic aggregation RDBMS functions that MongoDb also supports and with the code examples.

Back to top

What is the composition/structure of ObjectId in MongoDB? Explain in detail each composing element.

ObjectId in MongoDb plays a very special role. It associates with _id field, and MongoDb uses objectid as the default value of _id in documents.

As we know Object is of type BSON. Object is 12 byte bson type data structure. The composition/structure of ObjectId is as follows :

  • The first 4 bytes represents the seconds since last unix time.
  • The next 3 bytes after first four are the machine identifier.
  • The next 2 bytes after the machine identifier are the process id.
  • The last 3 bytes after machine identifier is some random counter value.

This represents the object id structure in a whole. To generate object id, MongoDb provides function as objectId(), syntax for the same is below :

ObjectId([SomeHexaDecimalValue])

Lets take example of creating ObjectId:

obj_id = new ObjectId()

The above statement will return the unique hexadecimal string containing object id as below:

ObjectId("6539h6hgt8721s97w45798j7")

We can also provide some unique hexadecimal string object id of 12 byte in method parameter, lets take an example:

Custom_obj_id = new ObjectId("2569j6hgt8621s97w45798j7")

There are some methods of ObjectId, below are the details :

  • str : provides string representation of object id.
  • valueOf() : returns the hexadecimal representation of ObjectId.
  • getTimeStamp() : returns the creation timestamp of objected.
  • toString() : returns the string representation of ObjectId in the “ObjectId(haxstring)”

Back to top

Explain GridFS in MongoDB? Give a practical example with source code for adding files to GridFS.

Let say we need to store large data files in MongoDb, how to do that, in a single document ? No, since MongoDb has limitation for a document to have maximum size of 16MB. Now how about storing data which has size more than 16 GB. In such scenarios GRIDFS comes to rescue us. GridFs is a MongoDb specification that enables us to store data that has size more than 16MB.  These large files can be some audio files or large images or might be a video file. In a way it is a kind of file system storage but still the data is store in MongoDb collections.

GridFS divides a large record ie a file into small chunks and it stores these chunks of data in documents, and each document has the maximum size of 255 kb.

GridFs uses two collections to store the large data, one collection is used to store the file chunks and other one is to store its metadata. These two collections are known as fs.files and fs.chunks to store file metadata and chunks.

When we want to retrieve the large dataset from MongoDb server, the MongoDb drivers reassembles the data from chunks and returns the data to calling function.

Syntax to store file using GridFs is:

mongofiles.exe -d <database_name> put <file_name>

To find the document in the database, find() method is used, below is the syntax for the same:

db.fs.files.find({filename : <file_name>})

Lets take an example to store a large file in mongo db server :

To store a file we need to traverse through the bin directory of mongodb installation:

Lets suppose we need to store the below file that is around 52MB in size. GridFS in MongoDBLets try to store this file using GridFS.Files using GridFS

As we can see the BookStoreDB has now the video file that is of 52 mb, and the file has been stored.

Lets try to find the file that we have just stored:Video File in MongoDB

As we can see in the output, we just got the file data from GridFs that we have stored.

To get all the chunks present, we can use the following command:MongoDB Commands

Running this file will return all the chunks. Notice we have used the files_id, as we got in the find command with chunks.

Back to top

How database relationship(1:1,1:N,N:1) is maintained in MongoDB? Explain with proper example.

Like relational database where records are relationally referenced in different tables maintaining the relationship as one to one (1:1), one to N (1:N), N to one (N:1), N to N (N:N). Relationship in MongoDB represents the way documents are logically connected to each other. In MongoDb these relationships are modeled in two ways :

  • Embedded
  • Referenced

Lets take an example of our BookStore application, where user can take one to N books on rent. Here in our database this relationship will be relationship will be in One to N (1:N).

Lets try to achieve this using the Embedded approach:MongoDB Inserts

As we can see in the example above we have inserted record with embedded approach, Here Alax user has two books Head First Java and Head First Design Patterns. In the embedded approach a single documents have the embedded records referenced. This approach have all the related data in the single document and if we need to find the whole document below will be the query to find one:MongoDB Find Command

As we can see from the query above, it resulted us the whole document that we have inserted.

So in essence in the embedded approach, we have all the related documents/records in a single document.

Now let’s move to another approach that is Reference approach :

In this approach instead of having all document in a single document, we will have separate document and these are referenced with ObjectId.MongoDB Reference with ObjectId

As we can see in the example above, the object ids are just dummy ids for demo purpose. In the next section we will be taking an example wherein we will insert two separate book records and we will be referencing these documents through their ObjectIds.

Lets try to store the Book documents and try to find to get the object id with which we will be referencing:Store Document in MongoDB

In the example above we have inserted two records for two books, Head First Java and Head First Design Pattern. And in the next step we have tried to find the records and we can see the inserted records in the BookStoreDB.

Now lets try to reference the documents to a user with reference approach:Referenced Way in MongoDB

This way we can store the records in referenced way in MongoDB.

Back to top

What are atomic operations? How automicity is achived in MongoDB, explain with example.

Atomicity is an important aspect of database that comes under ACID concept. NoSql databases have some difference with respect to handle atomicity as compared to traditional relational database systems and so as MongoDB. Lets try to understand what automicity is : Automicity is a concept where in while updating some records in the database either all records should update in a transaction or no record should update. Basically we can refer it to an atomic transaction.  What automicity garuntees is either all records of database will update in a transaction or no record will update, that prevents the partial updation.

MongoDb also supports automicity but as we discussed in some different manner. In MongoDB there is a constraint that only one document can be updated as part of a single transaction. There can be multiple documents in a single document and it can be updated keeping automicity, but if there will be multiple documents then automicity cannot be achieved in MongoDb, so in essence we can achieve automicity in MongoDb but on a single document.

So what if we still we want to achieve automicity on multiple documents, here you need to use two phase commit to achieve the same. But the recommended approach to achieve automicity is to have the embedded documents, ie. To have all the related documents in one place.

Lets try to understand the same with help of an example:

Lets suppose we have a book store and in our bookstore we are maintaining the total number of “Head First Java” books and the remaining number of books, also at the same time we are maintaining the record about the user who bought the book. So a buy operation from frontend, and the below actions will performed at backend :

  • Decrese the available number of books by 1.
  • Update the Buyer Information with the user details who bought this book.

Below is how the document looks like for the same:

{
    "_id":"sr888377jjfjj3333",
    "book_name":"Head First Java",
    "total_books":100,
    "book_category":"Computer Science",
    "available_books":78,
    "Buyer Information": [
        {
            "name":"Alex",
            "email_id":"alex@yahoo.com"
        },
        {
            "customer":"Jimmy",
            "date":"jimmy@yahoo.com"
        }
    ]
}

So as we can see we have embedded the Buyer Information document with this in order to achieve atomicity. Whenever a buy book request will made from front end, at database side first it will check for the available number of books, if the available number of books is greater than 0, then the available books count will be decreased by one and the buyer information will be updated in the embedded document, Buyer Information that is embedded with the main document.

To update a document in MongoDb we will use findAndModify() method. Let’s take an example with the scenario above how we can use the findAndModify() method:

>db.BookStoreDB.findAndModify({ 
   query:{_id: "sr888377jjfjj3333" , available_books:{$gt:0}}, 
   update:{ 
      $inc:{available_books:-1}, 
      $push:{Buyer Information:{name:"Bjorn",email_id:"bjorn.smith@yahoo.com"}} 
   }    
})

The above code fragment first checks that if the available books are greater then zero, if the count is greater than zero than in the update part first decrease the count of available books by 1 and add the buyer information in the Buyer Information embedded document.

Back to top

Explain MapReduce in MongoDb with example?

MapReduce is a concept of processing large set of data and return an aggregated result.

From MongoDb official site :
“Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results. For map-reduce operations, MongoDB provides the mapReduce database command.”

MapReduce is usually used where we need to process large datasets.

Lets go through the map reduce command in MongoDb:

db.runCommand(
{
    mapReduce : <Collection_Name>	
    map: function()
    {
         //map function
    },
    reduce: function(key,values)
    {
        //reduce function
    },
    {
        out: collection,
        query: document,
        sort: document,
        limit: number
    }
})

Lets go through each term used in command one by one :

map, maps value with key and emits a key,value pair.

reduce, reduces the key value pair and group all the values with same keys.

out, indicates the location to put the result.

query, indicates if there is any thing that needs to be selected based on some criteria.

sort, Boolean field, indicates that the result needs to be sorted or not.

limit, is the number of documents that needs to be returned.

Let’s now try to understand the same with help of an example. Consider a scenario where have a online portal and we are getting a kind of items from different companies. Typically our document structure is like:

{
	Item_name : “Sony Xperia-z”,
	Category : “mobile_phone”,
	Company : “Sony”
}

Using this type of recordsets we will use map reduce to do some stuff. Lets first insert some records in our online portal database.MapReduce in MongoDB

So our onlineportal database is ready and we have populated some records for MobilePhone category. Now Lets play with map reduce features :

Suppose we want to count the number the items from each company, below is how we will write command for the same using MapReduce:MongoDB MapReduce Commands

As we can see, we wrote a command used company in map and used the key in reduce function, with a counter. In results section we got the expected result that Company Apple have 5 products/items in our db, Samsung has 4 and sony has 4.

Now in another requirement we want to count the number of MobilePhones that have Price greater then 40000, lets see how we can achieve this :

We will use query in this case and we will try to find out the records that have price greater then 40000. Below is the example:Query MongoDB

As we can see, we have the results now and in the way we wanted, Apple has 2 phones that have Price greater then 40000, Samsung has 1 and Sony has 3. If you give a close look at the command that we have used here from the last example we have just added a new thing here that is query,  and added the condition what we required and map reduce gave us the results in a flash.

This way we can process a very large dataset in our application using MapReduce.

Back to top

What is capped collection in MongoDb? How capped collections are created in MongoDb?

Capped collection is a special kind of collection in MongoDb, what can have limit on collection storage. That means in this collection we can restrict the size of collection or we can put limit on size of collection, these special type of collection is named as Capped Collection.

Lets take a look at the syntax of creating capped collection:

db.createCollection(<Collection_Name>, {capped: Boolean, autoIndexId: Boolean, size: Number, max : Number})

The syntax is near about same as the syntax of creating collection. Lets understand the syntax first :

Collection_Name : Name of collection that needs to be created as capped collection.

capped : Capped is the Boolean flag, true if the collection needs to created as capped collection, by default the value is false.

autoIndexId : Boolean flag, used for autoindexing, if true indexes will be created automatically, false will say indexes will not be created automatically.

size : Size parameter says the max size of documents in bytes, it is mandatory field in case of capped collections.

max : max parameter says the max number of documents allowed in a collection. Size is given preference over size.

MongoDb provides a method isCappped() to check if the collection is capped or not. Below is the syntax for the same:

db.<Collection_Name>.isCapped()

Back to top

Give a practical example of creating Capped Collection in MongoDB?

Let’s try to create a capped collection and try to simulate with some number of documents:

Consider a scenario wherein we have a bookstore application and we are logging the user data, and we want this data shouldn’t go over 3 documents. So we will be creating a capped collection that will have of capped collection type and have the restriction of keeping 3 documents, just to simulate this our example will not have the actual log data but just the documents having dummy data.

Lets first start with creating a capped collection in our BookStoreDB:

Capped Collections in MongoDB

Here we have created a collection named Logs as capped collection and provided the max document as 3 and max size as 200Bytes. In next command we have checked with the method isCapped() that if the collection is capped or not.

Let’s try to insert data in our collection:Insert Data in MongoDB Collection

So till now we have created a capped collection with max size of 3 documents, we have inserted three documents and the same reflected in the find command. Now since the collection is size of 3 documents and its now reached its threshold, now if we add another document, the oldest one will be overridden by newer one.

Let’s create a new record and try to find the documents in the collection:

Find Document in MongoDB Collection

So we have inserted a new document, lets try to list the documents now:

Insert new document in MongoDB

So as we can see the old document of user John is overridden now, since the Logs collection is capped collection and of the max size of 3 documents.

Capped collections are useful for log files, these collections only allow updates on original document size which ensures that the document will not change its location on disk. The same is also a disadvantage as well since if the update go beyond the size then the update will fail. One more disadvantage is that we cannot delete a document from capped collection.

Back to top

Does MongoDb support regular expressions? If yes, explain searching in MongoDb with regular expression. Implement an example.

Regular expressions are used in software applications among various languages to find pattern from a string or from a document or from database. MongoDb also have support for regular expressions. In relational database systems we use like and % for pattern matching in string. In MongoDb as well the same can be achieved using pattern matching as well as using regular expressions.

Lets understand the same with example:

To start with this we will add some data in a collection. In our BookStoreDB, we are going to add some books with name, author and isbn number.Add Books to MongoDB

So in our allbooks collection, we have inserted some records for books. Now lets try to search in our collection using regex :

Syntex to search some string in document from json is:

db.<Collection_Name>.find( {<fieldname> : { $regex : <Pattern> }} )

Lets understand the syntax :

Collection_Name is the name of collection under which we need to perform searching.

FieldName is the name of key, whose value needs to be find with regex.

$regex is the regular expression syntax in MongoDB.

Pattern is the pattern which needs to be search.

Lets apply the syntax and try to search from the allbooks collection, where we need to find the book name which have “Java”.Regular Expressions in MongoDB

As we can see we got the results that have value as Java.

Now there might be scenario where we need to search for exact string, let suppose we have one more book that has name as “JavaScript In Web”, and if we will try to apply our search we will get the same in result as well, since JavaScript have the Java word in it. To avoid such scenarios there are some special characters available in MongoDb that comes in action to rescue, there are $ and ^.

^ (Caret) used to make sure that the string should start with the character given in pattern whereas $ used to make sure that the string should end the character given in the pattern.

If we want to make our search case insensitive then we need to use $options with our search.Regex in MongoDB

If we don’t want to use regex for pattern matching, then there is another option available that is to use /<pattern>/ in find command, below is the syntax for the same: Regex Patterns in MongoDBThis is all about pattern matching using regex in MongoDb.

Back to top

This mini NodeJS course will help you learn how to design your own eCommerce website using NodeJS, Express and Kraken. NodeJS is a brilliant open-source JavaScript runtime environment that allows developers to create powerful and dynamic server-side web applications.

In this project-based course, you will build an entire Bookstore from scratch. You will be able to add, edit and delete books to the backend and customers will be able to browse, add and delete books from their cart as well as purchase it using Paypal.

NodeJS Course
Take this Course Online Now

Hopefully, this series of MongoDB Interview Questions with detailed answers including source code will be an ultimate source for Interview preparation. Next we are going to cover more MEAN Stack related topic, so keep in touch 🙂

Top Technical Interview Questions and Answers Series:

The post Advanced MongoDB Interview Questions appeared first on Web Development Tutorial.

Viewing all 26 articles
Browse latest View live




Latest Images