XML Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on XML

Note: In this chapter, we will first just skim through basic XML interview questions so that you do not 
get stuck up with simple questions.

Question 1.
What is XML? (B)What is XML?
Answer:
XML (Extensible Markup Language) is all about describing data. Below is a XML, which describes invoice data.

<?xml version="1.0 " encoding=''ISO-8859-1" ?>
<invoice>
<productname>Shoes</productname>
<qty>12 </qty>
<totalcost>100</totalcost>
<discount>10</discount>
</invoice>

An XML tag is not something predefined but it is something you have to define according to your needs. For instance, in the above example of the invoice, all tags are defined according to business needs. The XML document is self-explanatory; anyone can easily understand looking at the XML data what exactly it means.

Question 2.
What is the version information in XML?
Answer:
“Version” tag shows which version of XML is used.

Question 3.
What is the ROOT element in XML? (B)What is the ROOT element in XML?
Answer:
In our XML sample given previously,<invoice></invoice> tag is the root element. Root element is the top most elements for a XML.

Question 4.
If XML does not have a closing tag will it work?
Answer:
No, every tag in XML, which is opened, should have a closing tag. For instance, at the top, if I remove the </discount> tag that XML will not be understood by a lot of applications.

Question 5.
Is XML case-sensitive?
Answer:
Yes, they are case-sensitive.

Question 6.
What is the difference between XML and HTML?
Answer:
XML describes data while HTML describes how the data should be displayed. Therefore, HTML is about displaying information while XML is about describing information.

Question 7.
Is XML meant to replace HTML?
Answer:
No, they both go together one is for describing data while the other is for displaying data.

Question 8.
Can you explain why your project needed XML?
Answer:

Note: This is an interview question where the interviewer wants to know why you have chosen XML.

Remember XML was meant to exchange data between two entities as you can define your user-friendly’ tags with ease. In real-world scenarios, XML is meant to exchange data. For instance, you have two applications that want to exchange information. However, because they work in two completely opposite technologies it is difficult to do it technically. For instance, one application is made in Java and the other in. NET. However, both languages understand XML so one of the applications will spit XML file, which will be consumed and parsed by other applications

You can give a scenario of two applications, which are working separately, and how you chose XML as the data transport medium.

Question 9.
What is DTD (Document Type Definition)?
Answer:
It defines how your XML should structure. For instance, in the above XML, we want to make it compulsory to provide “qty” and “total cost”, also that these two elements can only contain numeric. Therefore, you can define the DTD document and use that DTD document within that XML.

Question 10.
What is well-formed XML?
Answer:
If an XML document is confirming to XML rules (all tags started are closed, there is a root element, etc) then it is a well-formed XML.

Question 11.
What is a valid XML?
Answer:
If XML is confirming DTD rules then it is a valid XML.

Question 12.
What is the CDATA section in XML?
Answer:
All data is normally parsed in XML but if you want to exclude some elements, you will need to put those elements in CDATA.

Question 13.
What is XSL?
Answer:
XSL (extensible Style Sheet) Language is used to transform XML documents into some other document. Therefore, its transformation document can convert XML to some other document. For instance, you can apply XSL to XML and convert it to HTML documents or probably CSV (Comma Separated Value) files.

Question 14.
What is element and attributes in XML?
Answer:
In the below example invoice is the element and the in number the attribute.

<invoice in number=1002x/invoice>

Question 15.
Which are the namespaces in .NET used for XML?
Answer:
“System.xml.dll” is the actual physical file, which has all XML implementation. Below are the commonly used namespaces:

  • System.Xml
  • System.Xml.Schema
  • System.Xml, XPath
  • System.Xml.Xsl

Question 16.
What are the standard ways of parsing XML documents?
Answer:
XML parser sits in between the XML document and the application that want to use the XML document. Parser exposes a set of well-defined interfaces, which can be used by the application for adding, modifying, and deleting the XML document contents. Now whatever interfaces XML parser exposes should be standard or else that would lead to different vendors preparing their own custom way of interacting with XML documents.

There are two standard specifications, which are very common and should be followed by an XML parser:

DOM (Document Object Model)

DOM Is a W3C (World Wide Web Consortium) recommended way for creating XML documents. In DOM, we load the entire XML document into memory and allows us to manipulate the structure and data of the XML document.

SAX: Simple API for XML

SAX is an event-driven way for processing XML documents. In DOM, we load the whole XML document into memory and then the application manipulates the XML document (See Figure 18.1). However, this is not always the best way to process large XML documents, which have huge data elements. For instance, you only want one element from the whole XML document or you only want to see if the XML is proper which means loading the whole XML in memory will be quite resource-intensive. SAX parsers parse the XML document sequentially and emit events like start and end of the document, elements, text content, etc. Therefore, applications that are interested in processing these events can register implementations of callback interfaces. SAX parser then only sends those event messages, which the application has demanded.

XML Interview Questions in .NET chapter 18 img 1

Figure 18.2 is a pictorial representation of how the DOM parser works. Application queries the DOM Parser for the “quantity” field. DOM parser loads the complete XML file into memory.

XML Interview Questions in .NET chapter 18 img 2

DOM parser then picks up the “quantity” tag from the memory-loaded XML file and returns back to the application.

XML Interview Questions in .NET chapter 18 img 3

SAX parser does not load the whole DOM into memory but has an event-based approach. SAX parser while parsing the XML file emits events. For example, in Figure 18.3, its has emitted Invoice tag start event, Amount Tag event, Quantity tag event, and Invoice end tag event. However, our application software is only interested in quantity value. Therefore, the application has to register to the SAX parser saying that he is only interested in the quantity field and not any other field or element of the XML document. Depending on what interest the application software has SAX parser only sends those events to the application the rest of the events is suppressed. For instance in Figure 18.3 only quantity tag event is sent to the application software and the rest of the events are suppressed

Question 17.
In what scenarios will you use a DOM parser and SAX parser?
Answer:

  • if you do not need all the data from the XML file then the SAX approach is much preferred to DOM as DOM can be quite memory intensive. In short, if you need a large portion of the XML document it’s better to have DOM.
  • With the SAX parser, you have to write more code than DOM.
  • If you want to write the XML into a file, DOM is the efficient way to do it.
  • Sometimes you only need to validate the XML structure and do not want to retrieve any Data for those instances SAX is the right approach.

Question 18.
How was XML handled during COM times?
Answer:
During COM, it was done by using MSXML (Microsoft extensible Markup Language) 4.0. So old > languages like VB6, VC++ used MSXML 4.0, which was shipped with SP1 (Service Pack 1).

Note: This book will not show any samples as such for MSXML 4.0. So if anyone interested please 
do refer the same in MSDN and try to compile some sample programs.

Question 19.
What is the main difference between MSML and .NET Framework XML classes?
Answer:
MSXML supports XMLDOM and SAX parsers while .NET framework XML classes support XML DOM and XML readers and writers.
MSXML supports asynchronous loading and validation while parsing. For instance, you can send synchronous and asynchronous calls to a remote URL. However, as such, there is no direct support „ of synchronous and asynchronous calls in .NET framework XML. However, it can be achieved by using “System.Net” namespaces.

Question 20.
What are the core functionalities in the XML .NET framework? Can you explain in detail those functionalities?
Answer:
The XML API for the .NET Framework comprises the following set of functionalities:

XML readers: With XML readers, the client application gets a reference to instances of reader class. Reader class allows you to scroll forward through the contents like moving from node to node or element to element. You can compare it with the “SqlDataReader” object in ADO.NET, which is forward only, in short, XML reader allows you to browse through the XML document.

XML writers: Using XML writers, you can store the XML contents to any other storage media. For instance, you want to store the whole in-memory XML to a physical file or any other media.

XML document classes: XML documents provide a in-memory representation for the data in an XMLDOM structure as defined by W3C. It also supports browsing and editing of the document. Therefore, it gives you a complete memory tree structure representation of your XML document.

Question 21.
What is XSLT?
Answer:
XSLT (extensible Stylesheet Language Transformations) is a rule-based language used to transform XML documents into other file formats. XSLT is nothing but generic transformation rules, which can be applied to transform XML documents to HTML, CS, Rich text, etc.

XML Interview Questions in .NET chapter 18 img 4

You can see in Figure 18.4 how the XSLT processor takes the XML file and applies the XSLT transformation to produce a different document.

Question 22.
Define XPath?
Answer:
It is an XML query language to select specific parts of an XML document. Using XPath, you can address or filter elements and text in an XML document. For instance, a simple XPath expression like “Invoice/ Amount” states find “Amount” node that is Chilean of “Invoice” nodes.

Question 23.
What is the concept of XPointer?
Answer:
XPointer is used to locate data within XML document. XPointer can point to a particular portion of a XML document, for instance
address.xmlttxpointer (/descendant: : streetnumber[@id=9])
So the above XPointer points street number=9 in “address .xml”.

Question 24.
What is an XMLReader Class?
Answer:
It is an abstract class available from the System.XML namespace. XML reader works on a read-only stream browsing from one node to other in a forward direction. It maintains only a pointer to the current node but has no idea of the previous and the next node. You cannot modify the XML document, you can only move forward.

Question 25.
What is XMLTextReader?
Answer:
The “XmlTextReader” class helps to provide fast access to streams of XML data in a forward-only and read-only manner. It also checks if the XML is well-formed. However, XMLTextReader does not validate against a schema or DTD (Document Type Definition) for that you will need “XmlNodeReader” or “XmlValidatingReader” class.

The instance of “XmlTextReader” can be created in a number of ways. For example, if you want to load the file from a disk you can use the below snippets.
XmlTextReader reader = new XmlTextReader (filename);

To loop through all the nodes you need to call the “read ().” method of the “XmlTextreader” object, “read ()” method returns “true” if there are records in the XML document or else it returns “false”.

//Open the stream
XmlTextReader reader = new XmlTextReader (file);
While (reader. Read( ))
{
          // your logic goes here 
         String pdata = reader. Value
}
// Close the stream 
Reader. Close ( );

To read the content of the current node on which the reader or/ect is you use the “value” property. As shown in the above code “data” gets the value from the XML using “reader . Value”.

Question 26.
How do we access attributes using “XmlReader”?
Answer:
The below snippets shows the way to access attributes. First in order to check whether there any attributes present in the current node you can use the “HasAttributes” function and use the “MoveToNextAttribute” method to move forward in attribute, in case you want to move to the next element use “MoveToElement () “.

if (reader.HasAttributes)
{
        while(reader.MoveToNextAttribute( ))
        {
               // your logic goes here
               string pdata = reader.Value
        }
}
reader.MoveToElement( );

Question 27.
Explain simple Walkthrough of XmlReader.
Answer:
In this section, we will do a simple walkthrough of how to use the “XmlReader” class. Sample for the same is available in both languages (C# and VB.NET) which you can find in “WindowsApplicationXMLVBNET” and “WindowsApplicationCSharp” folders. The task is to load the “TestingXML.XML” file and display its data in a message box. You can find the “TestingXML.XML” file in “BIN” directory of both folders. Figure 18.5 shows are the display of the “TestingXML.XML” file and its content.

XML Interview Questions in .NET chapter 18 img 5

Both the projects have the command button “CmdLoadXML” which has the logic to load the XML file and display the data in the message box (See Figure 18.6). I have pasted only the “CmdLoadXML” command button logic for simplicity. Following are the basic steps done:

  • Declared the “XMLTextReader” object and gave the XML filename to load the XML data.
  • Read the “XMLTextReader” object until it has data and concatenate the data in a temporary string.
  • Finally, display the same in a message box.

XML Interview Questions in .NET chapter 18 img 6

It holds true for the C# code as shown in Figure 18.7.

XML Interview Questions in .NET chapter 18 img 7

Figure 18.8 shows the output.

Question 28.
What does XmlValidatingReader class do?
Answer:
XmlTextReader class does not validate the contents of an XML source against a schema. The correctness of XML documents can be measured by two things is the document is well-formed and is valid. Well-formed means that the overall syntax is correct. Validation is much deeper which means is the XML document is proper with respect to the schema defined.

XML Interview Questions in .NET chapter 18 img 8

Therefore, the XmlTextReader only checks if the syntax is correct but does not do validation. There is where XmlValidatingReader class comes into the picture. Therefore, this again comes at a price as XmlValidatingReader has to check for DTD and Schema’s that is the reason they are slower compared to XmlTextReader.

Ajax Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Ajax

Question 1.
What problem does Ajax solve?
Answer:
In order to answer this question first let’s understand how do browsers and servers work when we request any Website. Figure 15.1 depicts pictorially the Web environment. When a client sends data to the server it postbacks from element data, hidden fields, images, cookie information to the server and the server makes the page and sends the same information back to the browser. The bad part this happens with every request and response.
Below are the issues with the above model:

• Unnecessary data transfers: In the model as shown in Figure 15.1, unnecessary data is transferred between client and server. For instance, the whole page is posted and refreshed even when we want small data of the page to be refreshed.

Ajax Interview Questions in .NET chapter 15 img 1

• Synchronous processing: When a user requests a page he/she has to wait until the complete round trip happens. In short, the request/response work on. asynchronous model as shown in Figure 15.2 rather than asynchronous which makes the user experience very difficult. How many times it has happened that you are requesting a page and you see the below screen…frustrating right.

Ajax Interview Questions in .NET chapter 15 img 2

• Unnecessary processing by the server: Because we are posting unnecessary information to the server, the server is overloaded with unnecessary processing.

Question 2.
What is Ajax?
Answer:
Ajax is a set of client-side technologies that provides asynchronous communication between user interfaces and Web servers. So the advantages of using Ajax are asynchronous communication, minimal data transfer, and the server is not overloaded with unnecessary load.

Question 3.
What is the fundamental behind Ajax?
Answer:
XMLHttpRequest is the fundamental behind Ajax. This allows the browser to communicate to a back-end server asynchronously. XMLHttpRequest object allows the browser to communicate with the server without posting the whole page and only sending the necessary data asynchronously.

Question 4.
How do we use XMLHTTPRequest objects in JavaScript?
Answer:
Below is a code snippet, which shows how to use the XMLHTTPRequest object (See Figure 15.3). In this code snippet, we are sending a GET request on the local IIS (Internet Information Services). Below is the explanation of the code snippet according to the numbers specified in the code snippet?

1, 2, 3, 4 – This is like checking which is this browser and create the objects accordingly. XMLHTTPRequest objects have different ways of technical implementation according to different browsers. In Internet Explorer, it is an ActiveX object but in other browsers it’s XMLHTTPRequest. So if windows.XMLHTTPRequest does not return null then we can create XMLHTTPRequest object. If it returns null then we can try creating the ActiveX object Microsoft.XMLHTTP object. In case it fails probably then probably we have an older version of XML that is MSXML2. So in the error handling, we will try to create the MSXML2 object.

Ajax Interview Questions in .NET chapter 15 img 3

5 – In this snippet, we OPEN the connection to the localhost server and specify what type of request we are using. In this case, we are using the GET method.
6 – Finally, we make a request to the server.
7 – Here we get the request sent by the server back to the client browser. This is a blocking call as we need to wait to get the request back from the server. This call is synchronous which means we need to wait for the response from the server.

Question 5.
Can you explain Scriptmanager control in Ajax?
Answer:
Script manager control is the central heart of Ajax. They manage all the Ajax-related objects on the page. Some of the core objectives of script manager control are as follows:

  • Helps load core Ajax-related script and library.
  • Provides access to Web services.
  • ASP.NET authentication, role, and profile services are loaded by script manager control.
  • Provided registration of server controls and behaviors.
  • Enable full or partial rendering of a Web page.
  • Provide localization features.

In short, any Ajax enable page should have this control.

Question 6.
What is the use of the update panel inAjax?
Answer:
Update panel is a component that enables sections ofASP.NET page to be partially rendered without a postback (See Figure 15.4).

Ajax Interview Questions in .NET chapter 15 img 4

Question 7.
How do we consume Web service in Ajax?
Answer:
In the script manager tag we need to specify the service reference path of the Web service URL (Uniform Resource Locator).

<asp: ScriptManager ID="ScriptManagerl" runat="server">
<Services>
<asp: ServiceReference Path="Customer.asmx" />
</Services>
</asp: ScriptManager>

We can then call the Customer object in the JavaScript client as shown in the below code snippet.

function LoadAll( )
{
          Customer.LoadCustomers(LoadCustomerToSelectOption, ErrorHandler, 
         TimeOutHandler);
}

Question 8.
Can you explain the concept of triggers in ‘UpdatePanel’ control?
Answer:
Triggers are child tags for the ‘UpdatePanel’ tag. Many times we would like to update the panel when some event occurs or a value change on a control. This can be achieved by using triggers. There are two types of triggers ‘ ControlEventTrigger’ and ‘ ControlValueTrigger’. So let’s first understand ‘ControlEventTrigger’. Using ‘ControlEventTrigger’ we define on which control and at which event the update panel should refresh. Below is a simple code snippet for ‘ControlEventTrigger’. ‘ControlEventTrigger’ are defined using ‘<atlas: ControlEventTrigger>’ tag. We have numbered the code snippet below so let’s understand the same with numbers:

1→We need to define ‘ControlEventTrigger’ using ‘<atlas: ControlEventTrigger> ‘tag.
2→In this sample we will link trigger in ‘ UpdatePanell’ with the click event of ‘Buttonl’.
3→In the ‘ <atlas : ControlEventTrigger>’ tag we need to define the control and event using
‘Controlld’ and ’ EventName’ properties, respectively.
So now when the button click event happens ‘ UpdatePanel 1’ is refreshed.

Ajax Interview Questions in .NET chapter 15 img 5

Using ‘ControlvalueTrigger’ we can update a panel when an external control has reached some value (See Figure 15.6). So again we need to define the same in a ‘Triggers’ tag. We need to put the ‘ControlvalueTrigger’ tag with control and property defined using the ‘Controlid’ property. So according to the below code snippet when the value of ‘ Textboxl’ changes we need to update the top panel.

Ajax Interview Questions in .NET chapter 15 img 6

Question 9.
Can you explain the ‘UpdateProgress’ component?
Answer:
Sometimes we have huge tasks at the back end for processing and we would like to show a user-friendly message until the processing finishes. That’s where the ‘ UpdateProgress’ control comes into the picture.

To use ‘UpdateProgress’ control we need to use ‘UpdatePanel’ tag. ‘UpdateProgress’ forms the child tag of ‘ UpdatePanel’ control. Until the server processing finishes we can display a message which can be defined in the ‘ ProgressTemplate’ tag which is the child tag of the ‘UpdateProgress ‘ tag (see Figure 15.7).

Ajax Interview Questions in .NET chapter 15 img 7

Question 10.
How can you do validations in Ajax?
Answer:
We can perform all the necessary validation like a required field, type checking, range checking, etc using Ajax. Below is a small snippet that shows how to use a required field validator. We have numbered the code snippet to understand the code more properly.

1→We have defined a text box ‘TextBoxI ’ which will be validated for the required field.
2→We have defined a simple ‘ <span>’ HTML tag which will display the error message.
3, 4, and 5 -> We use the XML declarative Ajax script to define that ‘ TextBoxI’ has validators and it’s a required field validator. To define the required field validator we need the ‘ RequiredFieldValidator’ controls inside the validators.
6→We then define where the error should be displayed using the ‘ validationErrorLabel’. In this case, we will be displaying an error in the span ‘ validator 1’ which was defined previously.

Ajax Interview Questions in .NET chapter 15 img 8

Note: The above sample shows a sample for ‘requiredFieldValidator’, but we can also use other validators
 like range validator, type validator, range validator, and regex validators.

Question 11.
How do we do exception handling in Ajax?
Answer:
Exception handling in Ajax is done using the ‘ ErrorTemplate’ which forms the child tag of ‘ script manager. There are three steps to achieve error handling in Ajax. Figure 15.9 in Ajax shows the three steps in a pictorial fashion.

Ajax Interview Questions in .NET chapter 15 img 9

Step 1 -> Right-click on the script manager and click ‘Create Error Template’.
Step 2 -> Once done click on ‘Edit Templates’.
Step 3 -> Enter which error message you want to display when there is an error and then finally click ‘End Template Editing’.
Just click back on the HTML view to see what we have in the HTML. You can see the ‘ ErrorTemplate’ tag is the fundamental driver for handling errors.

Question 12.
Can we have multiple “ScriptManager” controls on a single page?
Answer:
No, we cannot have multiple script manager control on a single page. Single script manager control can have multiple update panels to define partial sections of the page.

 

NET Interoperability Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on NET Interoperability

Question 1.
How can we use COM Components in .NET?
Answer:
.NET components communicate with COM using RCW (Runtime Callable Wrapper). Following are the ways with which you can generate RCW:

  • Adding reference in Visual Studio.NET. See Figure 19.1 (Adding reference using VS.NET 2005). Wrapper class is generated and placed in the “BIN” directory.

NET Interoperability Interview Questions in .NET chapter 19 img 1

  • UsingTypelibraryimporttool.Tlbimp.exeyourname.dll.

• Using interopservices .The system, runtime. Interopservic’es namespace contains class TypeLibConverter that provides methods to convert COM classes and interface into assembly metadata.
• Make your custom wrappers, if your COM component does not have a type library then the only way to communicate is by writing custom wrappers. That means communicating directly with COM components.

Question 2.
We have developed the COM wrapper do we have to still register the COM?
Answer:
Yes.

Question 3.
How can we use .NET components in COM?
Answer:
.NET components cannot be used in a straightforward way with COM. You will need to create CCW (COM Callable Wrapper) in order that COM components communicate with .NET assemblies. Following are the different approaches to implement it:

  • Explicitly declare interfaces.
Public Interface ICustomer
Property CustomerName( ) As String
Property CustomerCode() As String
Sub AddCustomer( )
End Interface
Public Class Customer
Implements ICustomer
Private PstrCustomerName As String
Private PstrCustomerCode As String
Public Sub AddCustomer() Implements ICustomer.AddCustomer
Try
' addin of database code can go here
Catch ex As Exception
Throw ex
End Try
End Sub
Public Property CustomerCode() As String Implements ICustomer.CustomerCode
Get
Return PstrCustomerCode
End Get
Set(ByVal value As String)
PstrCustomerCode = value
End Set
End Property
Public Property CustomerName() As String Implements ICustomer.CustomerName
Get
Return PstrCustomerName End Get
Set(ByVal value As String)
PstrCustomerName = value End Set
End Property
Public Sub New( )
End Sub
End Class

The above Customer class is going to be used by COM components so all the properties and methods are declared in the interface and implemented in the Customer class. CustomerName, CustomerCode, and AddCustomer are first declared in customer and then implemented in Customer Class. Also, note that the class must have a default constructor.

Note: All source code in this book is provided in VB.NET that does not mean that author of the book does 
not like C#. In fact, the main programming language of the author is C#. In order to keep things small,
 I have only used one language. However, the conversion is so seamless that it is of the least matter.
  • The second way to create CCW is by using interop services attributes. Here interfaces are created automatically.

Question 4.
Following are different types of class attributes:
Answer:
None: No class interface is generated for the class. This is the default setting when you do not specify anything.

AutoDispatch: Interface that supports IDispatch is created for the class. However, no type of information is produced.

Auto Dual: A dual interface is created for the class. Type information is produced and made available in the type library.
Below in the source code we have used the third attribute.

Imports System.Runtime.InteropServices
<ClassInterfaceAttribute (ClassInterfaceType.AutoDual)>
PublicClass ClsCompliant
EndClass

Other than class, attributes defined up there are other attributes with which you can govern another part of the assembly. Example “GuidAttribute” allows you to specify the GUiD (Globally Unique identifier),
“ComVisibleAttribute” can be used to hide .NET types from COM etc. All attributes are not in the scope of the book as this is an interview questions book refer to MSDN (Microsoft Developer Network) for more details.

NET Interoperability Interview Questions in .NET chapter 19 img 2

  • Once .NET assembly is created using either interface or using InteropServices method we need to create a COM type library using Type Library’ Export Tool.
    Tbsp (Assembly Name)

The final thing is registering the CCW in the registry using regasm Tool. reason Assembly Name [Options]

  • Finally refer to the TLB (Translation Lookaside Buffer) in your COM IDE (Integrated Development Environment) Figure 19.2 shows VB6 IDE referencing the DLL (Dynamic Link Library).
Note: DLL and TLB should be in the same directory where the application is executed.2..NET Interoperability

Question 5.
How can we make Windows API calls in .NET?
Windows API calls are not COM-based and they are invoked through Platform Invoke Services.

Declare StringConversionType (Function I Sub) MethodName Lib “DIIName” ([Args]) As Type

  • StringConversionType is for what type of conversion should take place. Either we can specify Unicode to convert all strings to Unicode values, or Auto to convert strings according to the .NET runtime rules.
  • MethodName is the name of the API to call.
  • DiiName is the name of the DLL.
  • Args are any arguments to the API call.
  • Type is the return type of the API call.

Below is a sample code for VB.NET, which uses sleep windows API for delaying.

Public Class Form1
Declare Auto Sub Sleep Lib "kernel32.dll" (ByVal dwMilliseconds As Long)
Private Sub Forml_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
MessageBox.Show(" start sleeping for 5000 Milli seconds . . . . . ")
Sleep(5000)
MessageBox.Show(" end of sleeping . . . . . ")
End Sub
End Class
Note: Source code is provided in CD in the “APICAL” folder. In VB.NET we use declare keyword but in C# it 
goes a little bit different, we need to use DllImport, InteropServices, and extern keyword. Below is a simple 
sample for the same.
#region Using directives using System;

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
#endregion
namespace CSharpCode
{
     partial class Form1: Form
     {
           [DllImport("Kernel32.dll")]
           static extern int Sleep(long dwMilliseconds); 
           public Forml()
           {
              InitializeComponent();
           }
           private void Forml_Load(object sender, EventArgs e)
           {
               MessageBox.Show("Starting of 5000 ms...");
               Sleep(5000) ;
               MessageBox.Show("End of 5000 ms...");
          }
    }
}

Question 6.
When we use windows API in .NET is it managed or unmanaged code?
Answer:
Windows API in .NET is unmanaged code.

Note: Even though VB6 and V C++ has gone off still many people do ask these old questions again and again. 
Still there are decent old application which are working with COM very much fine. So interviewer still asks you 
these questions so that those application’s can be ported to .NET. So let’s play some old music... By the way 
my favourite music is Kish ore, what’s yours???

Question 7.
What is COM?
Answer:
Microsoft’s COM is a technology for component software development. It is a binary standard, which is language independent. DCOM is a distributed extension of COM.

Question 8.
What is Reference counting in COM?
Answer:
Reference counting is a memory management technique used to count how many times an object has a pointer referring to it. The first time it is created, the reference count is set to one. When the last reference to the object is nulled, the reference count is set to zero and the object is deleted. Care must be exercised to prevent a context switch from changing the reference count at the time of deletion. In the methods that follow, the syntax is shortened to keep the scope of the discussion brief and manageable.

Question 9.
Can you describe the IUnknown interface in short?
Answer:
Every COM object supports at least one interface, the IUnknown interface. All interfaces are classes derived from the base class IUnknown. Each interface supports methods to access data and perform operations transparently to the programmer. For example, IUnknown supports three methods, AddRef, Released, and Querylnterf ace ( ). Suppose that pinterf is a pointer to an IUnknown.

pinterf->AddRef increments the reference count. pinterf->Release ( ) decrements the reference count, deleting the object when the reference count reaches zero, pinterf- >QueryInterface (IDesired, pDesired) checks to see if the current interface (IUnknown) supports another interface, IDesired, creates an instance (via a call to CoCreateinstance ()) of the object if the reference count is zero (the object does not yet exist), and then calls pDesired- >AddRef () to increment the reference count (where pDesired is a pointer to IDesired) and returns the pointer to the caller.

Question 10.
Can you explain what DCOM is?
Answer:
DCOM (Distributed Component Object Model) differs from COM in that it allows for creating objects distributed across a network, a protocol for invoking that object’s methods, and secures access to the object. DCOM provides a wrapper around COM, hence it is a backwards compatible extension. DCOM uses Remote Procedural Calls (RPC) using Open Software Foundation’s Distributed Computing Environment.

These RPC are implemented over TCP/IP (Transmission Control Protocol/Internet Protocol) and named pipes. The protocol, which is actually being used, is registered just prior to use, as opposed to being registered at initialization time. The reason for this is that if a protocol is not being used, it will not be loaded. »

In order to inform an object that the client is still alive, periodic pinging is used. Hence, when the client has died and no ping has been received (to refresh it) before the expiration time, the server object will perform some clean up tasks (including decrementing its reference count).
Since RPC across a network are typically slow (compared to processes residing on the same machine), DCOM sends multiple requests in the same call. For example, in COM, the program performs a Queryinterf ace, one interface at a time. In DCOM, multiple Querylnterfaces are all clustered into one call.

This clustering optimization trick is also used when creating an instance of the object and serializing it with data. Since these two operations usually occur together, DCOM allows one method, which will perform both operations in one call without waiting for an acknowledgment from the first task before performing the second one.

Similarly, when a client pings its server object, he can do it in one call. Moreover, if there are multiple clients sending pings to multiple servers, an optimization is made where the multiple pings going to the same object are consolidated into just one ping. This is to cut down on the use of precious bandwidth used only for pinging.

The client has the control to set the computer, which will be responsible for the lifetime of the object. That is to say, these objects are not created just somewhere where the system resources and access privileges allow for it.

Call security is implemented in all four ways: authentication (to prevent false clients from impersonating the true client), authorization (to insure that a client only does what it is authorized to do), data integrity (to insure that data was not tampered with during transit), and data privacy (to insure that only designated sources can read it). The security issues are handled as they are on operating systems. The client gives the server various access privileges to access memory or disk space.

Question 11.
How do we create DCOM object in VB6?
Answer:
Using the CreateObject method, you can create a DCOM object. You have to put the server name in the registry.

Question 12.
How to implement DTC in .NET?
Answer:
DTC (Distributed Transaction Coordinator) is implemented using COM+ (See Figure 19.3).
Following are the steps to implement COM+ in .NET:

  • “EnterpriseServices” namespace has all the classes by which we can implement DTC in .NETas shown in Figure 19.3. You have to add reference “EnterpriseServices” namespace.

NET Interoperability Interview Questions in .NET chapter 19 img 3

  • You class must derive from the “ServicedComponent” object.
  • Then you have to define your class with the transaction attribute.

(For all transaction attribute look at the down question)
[Transaction (TransactionOption.RequiresNew) ]

After the class level, the transaction type is defined. Its time to define at the method level the AutoComplete attribute. AutoComplete attribute says that if no exception is thrown then mark its part of the transaction as being okay. This helps cut down on the amount of code required. If the implementation sets AutoComplete to false, or omits it all together, then we would need to manage the transaction manually. To manually, control the transaction you will need to use the Contextutil class and its static members. Following is small snippet of Contextutil:

public void SampleFunction( )
{
     try
     {
          // Do something to a database
         //...
        // Everything okay so far Commit the transaction
        Contextutil.SetComplete();
    }
    catch(Exception)
    {
       // Something went wrong Abort and Rollback the Transaction.
       Contextutil.SetAbort();
    }
}
  • Component derived from “ServicedComponent” should be strongly named as they run under COM+.
  • Once the classes are compiled using the string name. Register the Component in COM+ services using:
    regsvcs c: \DIIPath\TransactionComponent.dll
  • You can see that the component is registered using the COM+ Explorer.

Question 12.
How many types of Transactions are there in COM + .NET?
Answer:
Five transactions types can be used with COM+. Whenever an object is registered with COM+, it has to abide either to these Five transaction types.

Disabled: There is no transaction. COM+ does not provide transaction support for this component.

Not Supported: Component does not support transactions. Hence even if the calling component in the hierarchy is transaction enabled this component will not participate in the transaction.

Supported: Components with transaction type support will be a part of the transaction. This will be only if the calling component has an active transaction. If the calling component is not transaction enabled this component will not start a new transaction.

Required: Components with this attribute require a transaction, i.e., either the calling should have a transaction in place else, this component will start a new transaction.

Required New: Components enabled with this transaction type always require a new transaction. Components with the required new transaction type instantiate a new transaction for themselves every time.

Question 13.
How do you do object pooling in .NET?
Answer:
COM+ reduces overhead by not creating object from scratch. So in CCM+ when object is activated it’s activated, from pool and when it has deactivated it is pushed back to the pool. Object pooling is configured by using the “ObjectPoolingAttribute” to the class.

Note: When a class is marked with objectpooling attribute it can not be inherited.
ObjectPooling(MinPoolSize: = 2, MaxPoolSize: = 5, CreationTimeout: = 20000)>
Public Class testingclass
Inherits ServicedComponent
Public Sub DoWork()
' Method contents go here.
End Sub
End Class

Above is a sample code, which has the “Objectpooling” attribute defined. Below is a sample code, which uses the class.

Public Class App
Overloads Public Shared Sub Main(args( ) As String)
Dim xyz As New TestObjectPooling( )
xyz.doWork( )
ServicedComponent.DisposeObj ect (xyz)
End Sub
End Class

Above is a sample code, which uses the object pooled object. Note the DisposeObj ect (). This ensures its safe return to the object pool.

Question 14.
What are types of compatibility in VB6?
Answer:
There are three possible project compatibility settings:

  • No Compatibility
  • Project Compatibility
  • Binary Compatibility

No Compatibility: With this setting, new class ID’s, new interface ID’s and a new type library ID will be generated by VB each time the ActiveX component project is compiled. This will cause any compiled client components to fail (with error 429!) and report a missing reference to the ‘VB ActiveX Test Component’ when a client project is loaded in the VB IDE (Integrated Development Environment).

Note: Use this setting to compile the initial release of a component to other developers.

Project Compatibility

With this setting, VB will generate new interface ID’s for classes whose interfaces have changed, but will not change the class ID’s or the type library ID. This will still cause any compiled client components to fail (with error 429!) but will not report a missing reference to the ‘VB ActiveX Test Component’ when a client project is loaded in the VB IDE. Recompilation of client components will restore them to working order again.

Note: Use this setting during the initial development and testing of a component within the IDE and before 
the component is released to other developers.(A)How many types of Transactions are there in COM + .NET ?

Binary Compatibility

VB makes it possible to extend an existing class or interface by adding new methods and properties, etc., and yet still retain binary compatibility. It can do this, because it silently creates a new interface ID for the extended interface and adds registration code to register the original interface ID but with a new Forward key containing the value of this new interface ID. COM will then substitute calls having the old ID with the new ID and hence applications built against the old interface will continue to work (assuming the inner workings of the component remain backward compatible!).

With this setting, Visual Basic will not change any of the existing class, interface or type library ID’s, however in order that it can do so, Visual Basic requires the project to specify an existing compiled version that it can compare against to eisure that existing interfaces have not been broken.

Question 15.
What is equivalent for regsvr32 exe in .NET?
Answer:
Regasm

Extra’s Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Extra’s

Question 1.
What is Multi-Targeting in .NET?
Answer:
In previous versions of Visual Studio, every version was tied up with a framework. For instance, Visual Studio 2003 only works with 1.1 and Visual Studio 2005 only works with 2.0.

Extra’s Interview Questions in .NET chapter 20 img 1

From Visual Studio 2008 they have added a multi-targeting feature. You can use the same Visual Studio with different versions of the .NET framework (See Figure 20.1). So if you click on project properties you can now change the framework version to different types and check if your code is compatible with the old version.

Question 2.
What are portable class libraries?
Answer:
The whole point of creating a class library project is reusability. Now we want this reusability not only within a .NET project,not across.NET not across.NET projects but across different types of .NET projects. now different types of .NET projects. Now different types of .NET projects mean projects which we create using templates of WPF, windows, Silverlight, windows phone, etc., as shown in figure 20.2.

Extra’s Interview Questions in .NET chapter 20 img 2

Now each one of these project types runs on different platforms and has different flavors of .NET frameworks. For example Silverlight
the application runs inside a browser and has a downsized version of.NET.
So in a Silverlight project if you try to reference a simple “Class project” you would end with a below error. That’s where portable class libraries are useful (See Figure 20.3). By creating a portable class we can reference it in any kind of .NET project type.

Extra’s Interview Questions in .NET chapter 20 img 3

To create a portable class we need to use the portable class template which is available in Visual Studio as shown in Figure 20.4.

Question 3.
What is NuGet?
Answer:
The number of frameworks and libraries from both Microsoft (MVC, EF, etc.) and Non-Microsoft open sources (NUnit, Log4Net, etc.) are huge in numbers. These frameworks and libraries keep updating to newer versions and it’s very difficult to keep a track of the same.

Extra’s Interview Questions in .NET chapter 20 img 4

As a Visual Studio developer if you need to reference these frameworks or libraries, you need to do the following:

  • Search the library URL (L. from Resource Locator).
  • Install the library or probably unzip it at someplace.
  • Reference the DLL in your Visual Studio Project.
  • If library demands also make appropriate changes to the App. config or Web. config file.

In case you want to revert back you need to follow the above process in a vice-versa fashion.
This is where “NuGet” makes our life easy. “NuGet” is a Visual Studio Extension that helps us to search, locate the library, download them, reference them in the Visual Studio project and also make appropriate changes to App and Web config files (See Figure 20.5).

Extra’s Interview Questions in .NET chapter 20 img 5

So once you click on “Manage NuGet Packages…”, you can go and search the framework and click on install. Figure 20.7 shows a simple image where I have searched the new version of the Entity framework and now we need to just click on the Install button to add the same to your Visual Studio Project.

Extra’s Interview Questions in .NET chapter 20 img 6

Question 4.
How can we Unit test private methods use VSTS?
Answer:
In order to invoke private methods in VSTS (Visual Studio Team System) unit test, we have a class called “PrivateObject”. Create the object of the “PrivateObject” class and pass the class whose private method needs to be invoked. In our case “negative” is the private method that has an integer input parameter. You can then use the “PrivateObject” object to invoke the private methods/functions as shown in the below code.

PrivateObject o = new PrivateObject(typeof(Maths));
boolb = Convert.ToBoolean(o.lnvoke(“lsNegative”, -1));

Question 5.
Is it good to practice Unit test Private methods?
Answer:
No. When we say Unit it’s a class. So if we test the public methods the private methods get tested internally as well. If you are testing private methods of a class that means there is something seriously wrong with the class design.

public classmates
{
     publicint Add(int numl, int num2)
     {
          if(IsNegative(numl) && IsNegative(num2))
          {
                  thrownewExcept ion ("Number should not be negative'');
          }
          return numl + num2;
    }
    privatebool IsNegative(int num)
    {
         if (num > 0)
         {
                returntrue;
         }
         else
         {
               returnfalse;
         }
    }
}

For instance, in the above “Maths” class there is a private function “IsNegative” if you are testing this method that means the “Maths” class is overloaded with responsibility. “Maths” class should only be doing arithmetic operations (Add, Subtract, etc.), but it is also loaded with the responsibility of doing validation.

So probably it’s a good idea to move the validation to a separate class called “Validator” which will do the numeric checks and then use this class inside the “Maths” class.

You can then write test cases on the “Validator” class separately which is a cleaner approach than the previous approach of using “PrivateObject” and invoking them via reflection.

public class Validator
{
      private bool IsNegative(int num)
      {
          if (num > 0)
          {
               return true;
          }
          else
          {
              return false;
          }
     }
}

Question 5.
What is Mock testing?
Answer:
Let’s say you want to Unit test a data access layer class. But before any call is made to the data access class it calls an email class. This email component is not functional because we have still not received email server configuration details. Below is a simple code with comments that depict this situation.

Extra’s Interview Questions in .NET chapter 20 img 7

So now how do we Unit test the data access layer because the Email class will never allow us to execute the data access layer code This is achieved by mocking ( bypassing ) the e-mail code

public class Email
{
      public bool SendEmail( )
      {
            // not configured throws error
      }
}

public class ClsCustomerDAL
{
       public bool SaveRecord(string strCustomerName)
       {
            Email obj = new Email( );
            obj.SendEmail(); // This line throws a error
 
            // Data acess code goes at this place but this place is never reached because
            // the error is throw in the previous line
            return true;
      }
}

Question 6.
How can we implement Mocking?
Answer:
You can implement mocking by using open source mocking frameworks like Rhino Mocks (a dynamic mock object framework for the .NET platform), MOQ
(Mock-you; mocking library for. NET), etc. For example, if we want to mock the Email class method by using the MOQ tool we need to write the below code. Create the Email object using the Mock class of the MOQ framework.

Mock<Email> target = new Mock<Email>( );

Then write the code which you want to execute rather than executing the actual code. For instance, now I want to just “return true” in a hard code manner.

target.Setup(x => x.SendEmail()).Returns(true);

Now any calls to the “target” email object will always return true.

Question 7.
So are we saying Microsoft does not have mock frameworks?
Answer:
In Visual Studio 2012, Microsoft has introduced “Fakes” which has two great features “Stubs” and “Shims” which will help us achieve mock testing.

Question 8.
Define code coverage.
Answer:
Code coverage is a measure used during software testing which describes how much part of your source code has been tested. So if you see that a critical part of your code is not tested by your test case probably you need to update the test case accordingly to get a better coverage result.

Extra’s Interview Questions in .NET chapter 20 img 8

To see how much code coverage has been done by test cases.
Click on the TESTt menu → Analyze Code Coverage →All Tests (See Figure 20.9).

Once the coverage runs its shows a detailed report as shown in Figure 20.10 stating which sections do not have coverage. For instance, in the below report it states that the “Calculate” method of maths has 25% code which is not covered by the test cases.

Extra’s Interview Questions in .NET chapter 20 img 9

Question 9.
What is Cyclomatic complexity and how to measure the same?
Answer:
Cyclomatic complexity helps you measure code complexity. The higher the code complexity, the more it is prone to errors, and more important it becomes a unit test for that specific code. Cyclomatic complexity number depends on how many different execution paths your code can execute depending on varying inputs. More the code paths, more the complexity.

For example, take the below code. There is nothing complex in the below code, we do not have many execution paths. We just have lots of code lines which does variable initialization. So the cyclomatic complexity of the below code is “1 ”.

public void cancel( )
{
     Num1 = 0;
     Num2 = 0;
     Operation = " ";
     Pie = 3.14;
     Num5 = 0;

        Operation1 =" ";
        Num2o = 0;
        Numx = 0;
        OperationStart = " ";
        PieMore = 3.145;
        Num6 = 0;
        Operationnew = " ";
}

But now take the example of the below code. There are 4 branch conditions in the below code as shown in below Table. So the cyclomatic complexity is “4”.

Input Output
Path 1 Operation. Length ==0 Exception thrown
Path 2 Operation == “+” Num1 + Num2
Path 3 Operation == “-“ Num1 – Num2
Path 4 Any other inputs Num1 * Num2
public int Calculate( )
{
      if (Operation.Length == 0)
      {
             throw new Exception!" Operation not specified");
      }
      if (Operation == "+")
      {
             return Num1 + Num2;
      }
      else if (Operation == "-";
      {
             return Num1 - Num2
      }
      else
      {
             return Num2 * Num1
      }
      return 0;
}

To measure code complexity using Visual Studio, click on Analyze -> Calculate Code Metric for the solution. This feature is available only for Visual Studio ultimate editions. Once done you should get the cyclomatic complexity as shown in Figure 20.11.

Extra’s Interview Questions in .NET chapter 20 img 10

Question 10.
What is the use of the extern keyword and DllImport attribute?
Answer:
If you want to call functions that are not written using the .NET framework, we need to use the extern keyword. So let’s say we want to call the “MessageBox” function which belongs to Windows API (Application Programming Interface). So the first thing we need to import the “interop services” namespace.

using System. Runtime. InteropServices;

Later we need to use the extern keyword to create the method as shown below. Also, note this method has to be decorated with “DllImport” attribute.

[Dlllmport(“User32. dll")]
public static extern int MessageBox(int h, string m, string c, int type);

Once the static function is created, you can call the “MessageBox” function later as shown in the below code.

MessageBox(0, “Test”, “My Message Box”, 0);

Question 11.
What is the difference between Debug and Release?
Answer:
Debug and Release are build modes, where Debug is used to build the code in development mode and Release is for production / go live as shown in Figure 20.12 environment.

Extra’s Interview Questions in .NET chapter 20 img 11

In Release mode, the code is more optimized and any debugging-related code or debug constants are removed before going to production.

Question 12.
What is the use of Debug directive?
Answer:
#DEBUG is a preprocessor directive. Now many times you want some code to run while you are debugging but you do want those codes shipped to the production environment.

For instance, in the below code we want to display the operating system only during debugging but this code we do not want to be pushed to the production server. To achieve this we can use the DEBUG directive.

You can see the below code, we have wrapped display operating version code in #if DEBUG condition.This code will be excluded when release compiling happens.

#if DEBUG
// This code will not be shipped to production.
Console.WriteLine(System.Environment.OSVersion);
#endif
// This code will be shipped to production,
for (int i = 0; i < 5 ; i++)
{
     Console.WriteLine(i);
}

Question 13.
What do the word scalability, scale-up, and scale-out mean?
Answer:
Scalability is the ability of a system to handle a growing amount of load without degrading performance. Consider you have a system which runs with 100 users efficiently. Let’s say over a period of time your load increases to 500 users, your system still has the ability to handle the load and provide the same efficiency.

You can achieve scalability in two ways either can Scale-up or Scale-out. In scale-up, we have only one machine and we increase the processing power of the machine by adding more processors, more RAMs (Random Access Memory), more hard disks, etc. So if your load increases you add more RAMs, more processors, etc., but you do not add extra physical machines.

In Scale-out, as your load increases, you add more computers and you have load balancers in front of those machines to distribute the load appropriately.

SQL SERVER Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on SQL SERVER

Note: This Chapter is too small to cover SQL Server completely. We suggest you buy our exclusive book 
SQL Server Interview Question book to gain full confidence during an interview for this product.

Question 1.
What is normalization?
Answer:

Note: A regular .NET programmer working on projects often stumbles in this question, which is but obvious. 
The bad part is sometimes the interviewer can take this as a very basic question to be answered and it can be 
a turning point for the interview. So let's cram it.

It is a set of rules that have been established to aid in the design of tables that are meant to be connected through relationships. This set of rules is known as Normalization.
Benefits of normalizing your database will include:

  • Avoiding repetitive entries
  • Reducing required storage space
  • Preventing the need to restructure existing tables to accommodate new data.
  • Increased speed and flexibility of queries, sorts, and summaries.
Note: During the interview candidates are expected to answer a maximum of three normal forms.

Following are the three normal forms:

First Normal Form
For a table to be in the first normal form, data must be broken up into the smallest units possible (See Figure 10.1). In addition to breaking data up into the smallest meaningful values, tables in first normal form should not contain repetitions groups of fields.

SQL SERVER Interview Questions in .NET chapter 10 img 1

In the example, as shown in Figure 10.1 City1 and City2 are repeating. In order that this table to be in the First normal form, you have to modify the table structure as follows. Also, note that the Customer Name is now broken down to the first name and last name (First normal form data should be broken down to the smallest unit) (See Table 10.2).

SQL SERVER Interview Questions in .NET chapter 10 img 2

Second Normal form
The second normal form states that each field in a multiple-field primary key table must be directly related to the entire primary key (See Figure 0.3). Or in other words, each non-key field should be a fact about all the fields in the primary key.

SQL SERVER Interview Questions in .NET chapter 10 img 3

In the above table of customers, City is not linked to any primary field (See Figure 10.4).

SQL SERVER Interview Questions in .NET chapter 10 img 4

That takes our database to a second normal form.

Third Normal form
A non-key field should not depend on another non-key field. The field “Total” is dependent on “Unit price” and “qty” (See Figure 10.5).

SQL SERVER Interview Questions in .NET chapter 10 img 5

Margin: This defines the spacing between the border and any neighboring elements.

SQL SERVER Interview Questions in .NET chapter 10 img 6

For instance below is a simple CSS code which defines a box with border, padding and margin values.

. box {
      width: 200px;
      border: 10px solid #9 9c;
      padding: 20px;
      margin: 50px;
}

Now if we apply the above CSS to a div tag as shown in the below code, your output would be as shown in the Figure 9.16. I have created two test. “Some text” and “Some other text” so that we can see how margin property functions.

SQL SERVER Interview Questions in .NET chapter 10 img 7

<div align="middle" class="box">
Some text 
</div>
Some other text

Question 2.
Can you explain some text effects in CSS 3?
Answer:
Here the interviewer is expecting you to answer one of two text effects by CSS. Below are two effects that are worth noting.

Shadow text effect
.specialtext
{
text-shadow: 5px 5px 5px #FF0000;
}

Figure 9.17 shows the shadow text effect.

SQL SERVER Interview Questions in .NET chapter 10 img 8

Word wrap effect

<style>
.breakword
{word-wrap: break-word;} 
</style>

SQL SERVER Interview Questions in .NET chapter 10 img 9

Question 3.
What are Web workers and why do we need them?
Answer:
Consider the below heavy for loop code which runs above million times.

function SomeHeavyFunction( )
{
      for (i = 0; i < 10000000000000; i++)
      {
           x = i + x ;
      }
}

Let’s say the above for loop code is executed on an HTML button click. Now, this method’s execution is synchronous. In other words, the complete browser will wait until the for loop completes.

<input type=”button”onclick=”SomeHeavyFunction();”/>

This can further lead to the browser getting frozen and unresponsive with an error message as shown in Figure 9.19.

SQL SERVER Interview Questions in .NET chapter 10 img 10

So if we can move this heavy for loop in a JavaScript file and run it asynchronously that means the browser does need to wait for the loop then we can have a more responsive browser. That is what the Web workers are for. Web worker helps to execute JavaScript files asynchronously.

Question 4.
What are the restrictions of the Web Worker thread?
Answer:
Web worker threads cannot modify HTML elements, global variables and some window properties like Window. Location. You are free to use JavaScript data types, XMLHTTPRequest calls, etc.

Question 5.
So how do we create a worker thread in JavaScript?
Answer:
To create a worker thread we need to pass the JavaScript file name and create the worker object.

var worker = new Worker(“MyHeavyProcess.js’);

To send a message to the worker object we need to use “PostMessage”, below is the code for the same.

worker.postMessage(“test”);

When the worker thread sends data we get it in the “OnMessage” event on the caller’s end.

worker.onmessage = function (e)
{
document.getElementByld("txt1").value = e.data;
} ;

SQL SERVER Interview Questions in .NET chapter 10 img 11

The heavy loop is in the “MyHeavyProcess.js” JavaScript file, below is the code for the same. When the JavaScript file wants to send message it uses “postMessage” and any message sent from the caller is received in the “onmessage” event.

var x =0
self.onmessage = function (e) {
for (i =0; i < 1000000000; i++)
{
x = i + x ;
}
self.postMessage(x);
} ;

Question 6.
How to terminate a Web worker?
Answer:

w.terminate( );

Question 7.
Why do we need HTML 5 server sent events?
Answer:
One of the common requirements in the Web world is getting updates from the server. Take the example of a stock ticker application where the browser has to take regular updates from the server for the recent stock value.

SQL SERVER Interview Questions in .NET chapter 10 img 12

Now to implement this kind of requirement developers normally write some kind of PULL code that goes to the server and fetches data in certain intervals. Now PULL solution is good but it makes the network chatty with a lot of calls and also it adds load on the server.

So rather than PULL, it would be great if we can have some kind of PUSH solution. In simple words when the server has updated it will send updates to the browser client. That can be achieved by using “Server-Sent Events” as shown in Figure 9.21.

So the first thing the browser needs to do is connect to the server source which will send updates. Let’s say we have page “stock.aspx” which sends stock updates. So to connect to the page we need to use attach to the event source object as shown in the below code.

var source = new EventSource(“stock.aspx”);

We also need to attach the function where we will receive messages when server sends update. For that we need to attach function to the “onmessage” event as shown in the below code.

source.onmessage = function (event)
{
document.getElementByld("result").innerHTML += event.data + "<br>";
};

Now from the server-side we need to send events. Below are some lists of important events with command that needs to be sent from the server-side.

Event command
Send data to the client Data: hello
Tell the client to retry in 10 seconds Retry: 10000
Raise a specific event with data Event: success

Data: you are logged in.

So now the “Total” field is removed and is the multiplication of Unit price * Qty.

Note: Fourth and Fifth Normal forms are left as homework to users.

Question 8.
What is denormalization?
Answer:
Denormalization is the process of putting one fact in numerous places (it’s vice-versa of normalization). Only one valid reason exists for denormalizing a relational design – to enhance performance or if we are doing data warehousing and data mining. The sacrifice to performance is that you increase redundancy in the database.

Question 9.
What are the different types of joins? What is the difference between them?
Answer:
INNER JOIN: Inner join shows matches only when they exist in both tables. For example, in the below SQL there are two tables Customers and Orders, and the inner join in made on Customers Customer id and Orders Customer id. So this SQL will only give you result with customers who have ordered. If the customer does not have an order, it will not display that record.

SELECT Customers. *, Orders. * FROM Customers INNER JOIN Orders ON Customers. CustomerlD =Orders. CustomerlD

LEFT OUTER JOIN: Left join will display all records in the left table of the SQL statement. In SQL below customers with or without orders will be displayed. Order data for customers without orders appears as NULL values. For example, you want to determine the amount ordered by each customer and you need to see who has not ordered anything as well. You can also see the LEFT OUTER JOIN as a mirror image of the RIGHT OUTER JOIN (Is covered in the next section) if you switch the side of each table.

SELECT Customers.*, Orders.* FROM Customers LEFT OUTER JOIN Orders ON Customers. CustomerlD -Orders.CustomerlD

RIGHT OUTER JOIN: Right join will display all records in the right table of the SQL statement. In SQL below all orders with or without matching customer records will be displayed. Customer data for orders without customers appear as NULL values. For example, you want to determine if there are any orders in the data with undefined CustomerlD values (say, after conversion or something like it). You can also see the RIGHT OUTER JOIN as a mirror image of the LEFT OUTER JOIN if you switch the side of each table.

SELECT Customers.*, Orders.* FROM Customers RIGHT OUTER JOIN Orders ON Customers. CustomerlD =Orders. 
CustomerlD

Question 10.
What is a candidate key?
Answer:
A table may have more than one combination of columns that could uniquely identify the rows in a table; each combination is a candidate key. During the database design, you can pick up one of the candidate keys to be the primary key. For example, in the Supplier table supplied and supplier name can be the candidate key but you will only pick up supplied as the primary key.

Question 11.
What are indexes and what is the difference between clustered and non-clustered?
Answer:
Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quickly.

There are clustered and non-clustered indexes. A clustered index is a special type of index that reorders the way in which records in the table are physically stored. Therefore, the table can have only one clustered index. The leaf nodes of a clustered index contain the data pages.

A non-clustered index is a special type of index in which the logical order of the index does not match the physical stored order of the rows on a disk. The leaf node of a non-clustered index does not consist of the data pages. Instead, the leaf nodes contain index rows.

Question 12.
How can you increase SQL performance?
Answer:
Following are tips that will increase your SQL performance:

  • Every index increases the time takes to perform INSERTS, UPDATES, and DELETES, so the number of indexes should not be too much. Try to use a maximum of 4-5 indexes on one table, not more. If you have a read-only table, then the number of indexes may be increased.
  • Keep your indexes as narrow as possible. This reduces the size of the index and reduces the number of reads required to read the index.
  • Try to create indexes on columns that have integer values rather than character values.
  • If you create a composite (multi-column) index, the orders of the columns in the key are very important. Try to order the columns in the key to enhance selectivity, with the most selective columns to the leftmost of the key.
  • If you want to join several tables, try to create surrogate integer keys for this purpose and create indexes on their columns.
  • Create a surrogate integer primary key (identity for example) if your table will not have many insert operations.
  • Clustered indexes are more preferable to nonclustered if you need to select by a range of values or you need to sort results set with GROUP BY or ORDER BY.
  • If your application will be performing the same query over and over on the same table, consider creating a covering index on the table.
  • You can use the SQL Server Profiler Create Trace Wizard with “Identify Scans of Large Tables” trace to determine which tables in your database may need indexes. This trace will show which tables are being scanned by queries instead of using an index.

Question 13.
What is DTS?
Answer:
DTS (Data Transformation Services) is used to import data and while importing it helps us to transform and modify data. The name itself is self-explanatory DTS.

Question 14.
What is the fill factor?
Answer:
The ‘fill factor’ option specifies how full SQL Server will make each index page. When there is no free space to insert a new row on the index page, SQL Server will create a new index page and transfer some rows from the previous page to the new one. This operation Is called page splits. You can reduce the number of page splits by setting the appropriate fill factor option to reserve free space on each index page. The fill factor is a value from 1 through 100 that specifies the percentage of the index page to be left empty.

The default value for the fill factor is 0. It is treated similarly to a fill-factor value of 100, the difference in that SQL Server leaves some space within the upper level of the index tree for FILLFACTOR = 0. The fill factor percentage is used only at the time when the index is created. If the table contains read-only data (or data that very rarely changed), you can set the ‘fill factor’ option to 100. When the table’s data is modified very often, you can decrease the fill factor to 70% or whatever you think is best.

Question 15.
What is RAID and how does it work?
Answer:
Redundant Array of Independent Disks (RAID) is a term used to describe the technique of improving data availability through the use of arrays of disks and various data-striping methodologies. Disk arrays are groups of disk drives that work together to achieve higher data transfer and I/O rates than those provided by single large drives. An array is a set of multiple disk drives plus a specialized controller (an array controller) that keeps track of how data is distributed across the drives. Data for a particular file is written in segments to the different drives in the array rather than being written to a single drive.

For speed and reliability, it is better to have more disks. When these disks are arranged in certain patterns and are use a specific controller, they are called a (RAID) set. There are several numbers associated with RAID, but the most common are 1, 5, and 10.
RAID 1 works by duplicating the same write on two hard drives. Let us assume you have two 20 GB drives. In RAID 1, data is written at the same time to both drives. RAID 1 is optimized for fast writes.

RAID 5 works by writing parts of data across all drives in the set (it requires at least three drives). If a drive failed, the entire set would be worthless. To combat this problem, one of the drives stores a “parity” bit. Think of a math problem, such as 3 + 7 = 10. You can think of the drives as storing one of the numbers, and the 10 is the parity part. By removing any one of the numbers, you can get it back by referring to the other two, like this: 3 + X = 10. Of course, losing more than one could be evil. RAID 5 is optimized for reads.

RAID 10 is a bit of a combination of both types. It does not store a parity bit, so it is faster, but it duplicates the data on two drives to be safe. You need at least four drives for RAID 10. This type of RAID is probably the best compromise for a database server.

Note: It is difficult to cover complete aspect of RAID in this book. It’s better to take some decent SQL Server 
book for in detail knowledge, but yes from interview aspect you can probably escape with this answer.

Question 16.
What is the difference between DELETE and TRUNCATE TABLE?
Answer:
Following are differences between them:

  • DELETE table can have criteria while TRUNCATE cannot.
  • The TRUNCATE table does not invoke trigger.
  • DELETE TABLE syntax logs the deletes thus make the delete operation slow. The TRUNCATE table does not log any information but it

logs information about deallocation of the data page of the table so the TRUNCATE table is faster as compared to delete the table.

Note: Thanks to all the readers for pointing out my mistake in the above question in my first edition. I had mentioned that the TRUNCATE table cannot be rolled back while the delete can be.

Question 17.
If locking is not implemented, what issues can occur?
Answer:
Following are the problems that occur if you do not implement locking properly in SQL Server.

Lost Updates: Lost updates occur if you let two transactions modify the same data at the same time, and the transaction that completes first is lost. You need to watch out for lost updates with the READ UNCOMMITTED isolation level. This isolation level disregards any type of locks, so two simultaneous data modifications are not aware of each other. Suppose that a customer has due of 2000$ to be paid. He/she pays 1000$ and again buys a product of 500$. Let’s say that these two transactions are now been entered from two different counters of the company.

Now both the counter user starts making, entry at the same time 10: 00 AM. Actually speaking at 10: 01 AM the customer should have 2000$-1000$+500 = 1500$ pending to be paid. But as said in lost updates the first transaction is not considered and the second transaction overrides it. So the final pending is 2000$+500$ = 2500$ I c hope the company does not lose the customer.

Non-Repeatable Read: Non-repeatable reads occur if a transaction is able to read the same row multiple times and gets a different value each time. Again, this problem is most likely to occur with the READ UNCOMMITTED isolation level. Because you let two transactions modify data at the same J time, you can get some unexpected results. For instance, a customer wants to book a flight, so the travel agent checks for the flight’s availability. The travel agent finds a seat and goes ahead to book the seat. While the travel agent is booking the seat, some other travel agent books the seat. When this travel agent goes to update the record, he gets an error saying that “Seat is already booked”. In short, the travel agent gets different status at different times for the seat.

Dirty Reads: Dirty reads are a special case of non-repeatable read. This happens if you run a report while transactions are modifying the data that you are reporting on. For example, there is a customer invoice report, which runs on 1: 00 AM (ante Meridien) in the afternoon and after that, all invoices are sent j to the respective customer for payments. Let us say one of the customers has 1000$ to be paid. Customer pays 1000$ at 1: 00 AM and at the same time report is run. Actually, the customer has no money pending but is still issued an invoice.

Phantom Reads: Phantom reads occur due to a transaction being able to read a row on the first read, but not being able to modify the same row due to another transaction deleting rows from the same table. Let us say you edit a record in the meantime somebody comes and deletes the record, you then go for updating the record which does not exist…Panicked.

Interestingly, the phantom reads can occur even with the default isolation level supported by SQL Server: READ COMMITTED. The only isolation level that does not allow phantoms is SERIALIZABLE, which ensures that each transaction is completely isolated from others. In other words, no one can acquire any type of locks on the affected row while it is being modified.

Question 18.
What are different transaction levels in SQL Server?
Answer:
Transaction Isolation level decides how is one process isolated from another process. Using transaction levels, you can implement locking in SQL Server.
There are four transaction levels in SQL Server:

READ COMMITTED: The shared lock is held for the duration of the transaction, meaning that no other transactions can change the data at the same time. Other transactions can insert and modify data in the same table, however, as long as it is not locked by the first transaction.

READ UNCOMMITTED: No shared locks and no exclusive locks are honored. This is the least restrictive isolation level resulting in the best concurrency but the least data integrity.

REPEATABLE READ: This setting disallows dirty and non-repeatable reads. However, even though the – locks are held on read data, new rows can still be inserted in the table, and will subsequently be interpreted by the transaction. v

SERIALIZABLE: This is the most restrictive setting holding shared locks on the range of data. This setting does not allow the insertion of new rows in the range that is locked; therefore, no phantoms are allowed. 4

Following is the syntax for setting transaction level in SQL Server. ;
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE

Question 19.
What are the different locks in SQL Server?
Answer:
Depending on the transaction level, six types of lock can be acquired on data:

Intent: The intent lock shows the future intention of SQL Server’s lock manager to acquire locks on a . specific unit of data for a particular transaction. SQL Server uses intent locks to queue exclusive locks, thereby ensuring that these locks will be placed on the data elements in the order the transactions were initiated. Intent locks come in three types: Intent Shared (IS), Intent Exclusive (IX), and Shared, with Intent Exclusive (SIX).

. IS locks indicate that the transaction will read some (but not all) resources in the table or page by placing shared locks.

IX locks indicate that the transaction will modify some (but not all) resources in the table or page by placing exclusive locks.

SIX locks indicate that the transaction will read all resources, and modify some (but not all) of them. 5 This will be accomplished by placing the shared locks on the resources read and exclusive locks on the rows modified. Only one SIX locks is allowed per resource at onetime; therefore, SIX locks prevent. other connections from modifying any data in the resource (page or table), although they do allow reading the data in the same resource.

Shared: Shared(S) locks allow transactions to read data with SELECT statements. Other connections are allowed to read the data at the same time; however, no transactions are allowed to modify data ‘ until the shared locks are released.

Update: Update(U) locks are acquired just prior to modifying the data. If a transaction modifies a row, then the update lock is escalated to an exclusive lock; otherwise, it is converted to a shared lock. Only one transaction can acquire update locks to a resource at one time. Using update locks prevents multiple connections from having a shared lock that wants to eventually modify a resource using an exclusive lock. Shared locks are compatible with other shared locks, but are not compatible with Update locks.

Exclusive: Exclusive(X) locks completely lock the resource from any type of access including reads. They are issued when data is being modified through INSERT, UPDATE, and DELETE statements.

Schema: Schema modification (Sch-M) locks are acquired when data definition language statements, such as CREATE TABLE, CREATE INDEX, ALTER TABLE, and so on are being executed. Schema stability locks (Sch-S) are acquired when store procedures are being compiled.

Bulk Update: Bulk Update (BU) locks are used when performing a bulk copy of data into a table with a TABLOCK hint. These locks improve performance while bulk copying data into a table; however, they reduce concurrency by effectively disabling any other connections to read or modify data in the table.

Question 20.
Can we suggest locking hints to SQL Server?
Answer:
We can give locking hints that help you override default decisions made by SQL Server. For instance, you can specify the ROWLOCK hint with your UPDATE statement to convince SQL Server to lock each row affected by that data modification. Whether it is prudent to do so is another story; what will happen if your UPDATE affects 95% of rows in the affected table? If the table contains 1000 rows, then SQL Server will have to acquire 950 individual locks, which is likely to cost a lot more in terms of, memory than acquiring a single table lock. So think twice before you bombard your code ROWLOCKS.

Question 21.
What is LOCK escalation?
Answer:
Lock escalation is the process of converting low-level locks (like rowlocks, page locks) into higher-level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards SQL Server dynamically manages it.

Question 22.
What are the different ways of moving data between databases in SQL Server?
Answer:
There are lots of options available; you have to choose your option depending upon your requirements. Some of the options you have are BACKUP/RESTORE, detaching and attaching databases, replication, DTS (Data Transformation Services), BCP (Bulk Copy Program), log shipping, INSERT…SELECT, SELECT…INTO, creating INSERT scripts to generate data.

Question 23.
What is the difference between a HAVING CLAUSE and a WHERE CLAUSE?
Answer:
You can use Having Clause with the GROUP BY function in a query and WHERE Clause is applied to each row before, they are part of the GROUP BY function in a query.

Question 24.
What is the difference between UNION and UNION ALL SQL syntax?
Answer:
UNION SQL syntax is used to select information from two tables. But it selects only distinct records from both the table, while UNION ALL selects all records from both the tables.

Note: Selected records should have same datatype or else the syntax will not work.

Question 25.
How can you raise custom errors from stored procedures?
Answer:
The RAISERROR statement is used to produce an ad hoc error message or to retrieve a custom message that is stored in the sys messages table. You can use this statement with the error handling code presented in the previous section to implement custom error messages in your applications. The syntax of the statement is shown here.

RAISERROR ((msg_id |msg_str }{, severity, state }
[, argument n ]]))
[ WITH option [,, ...n ] ]

A description of the components of the statement follows.

mug_id: The ID for an error message, which is stored in the error column in sys messages.

msg_str: A custom message that is not contained in sys messages.

Severity: The severity level associated with the error. The valid values are 0-25. Severity levels 0-18 can be used by any user, but 19-25 are only available to members of the fixed-server role sysadmin. When levels 19-25 are used, the WITH LOG option is required.

State A value that indicates the invocation state of the error. The valid values are 0-127. This value is not used by SQL Server.
Argument…
One or more variables are used to customize the message. For example, you could pass the current process ID (@@SPID) SO it could be displayed in the message.
WITH option,…
The three values that can be used with this optional argument are described here.

LOG: Forces the error to log in the SQL Server error log and the NT application log.

NOWAIT: Sends the message immediately to the client.

SETERROR: Sets @@ERROR to the unique ID for the message or 50, 000.

The number of options available for the statement makes it seem complicated, but it is actually easy to use. The following shows how to create an ad hoc message with a severity of 10 and a state of 1:
RAISERROR (‘An error occurred updating the Nonfatal table’, 10,1)

—Results—

An error occurred in updating the non-fatal table.
The statement does not have to be used in conjunction with any other code, but for our purposes, it will be used with the error handling code presented earlier. The following alters the
ps_NonFatal_iNSERT procedure to use RAISERROR:

USE tempdb

go

ALTER PROCEDURE ps_NonFatalJNSERT

@Column2 int =NULL AS.
DECLARE ©ErrorMsglD int
INSERT NonFatal VALUES (@Column2)
SET @ErrorMsgID =@@ERROR IF OErrorMsgID <>0 BEGIN
RAISERROR ('An error occured updating the NonFatal table', 10, 1)
END

When an error-producing call is made to the procedure, the custom message is passed to the client.

Question 26.
What is ACID fundamental?
Answer:
A transaction is a sequence of operations performed as a single logical unit of work. A logical unit of work must exhibit four properties, called the ACID (Atomicity, Consistency, Isolation, and Durability) properties, to qualify as a transaction:

Atomicity: A transaction must be an atomic unit of work; either all of its data modifications are performed or none of them is performed.

Consistency: When completed, a transaction must leave all data in a consistent state. In a relational database, all rules must be applied to the transaction’s modifications to maintain all data integrity.

isolation: Modifications made by concurrent transactions must be isolated from the modifications made by any other concurrent transactions. A transaction either see data in the state it was before another concurrent transaction modified it, or it sees the data after the second transaction has completed, but it does not see an intermediate state. This is referred to as serializability because it results in the ability to reload the starting data and replay a series of transactions to end up with the data in the same state it was in after the original transactions were performed.

Durability: After a transaction has completed, its effects are permanently in place in the system. The modifications persist even in the event of a system failure.

Question 27.
What are the different types of triggers in SQI Server?
Answer:
There are two types of triggers:

INSTEAD OF triggers: INSTEAD OF triggers fire in place of the triggering action. For example, if an INSTEAD OF UPDATE trigger exists on the Sales table and an UPDATE statement is executed against the Sales table, the UPDATE statement will not change a row in the sales table. Instead, the UPDATE statement causes the INSTEAD OF UPDATE trigger to be executed.

AFTER triggers: AFTER triggers execute following the SQL action, such as an insert, update, or delete. This is the traditional trigger that existed in SQL Server.

INSTEAD OF triggers are executed automatically before the Primary Key and the Foreign Key constraints are checked, whereas the traditional AFTER triggers are executed after these constraints are checked.
Unlike AFTER triggers, INSTEAD OF triggers can be created on views.

Question 28.
If we have multiple AFTER Triggers, can we specify sequence?
Answer:
If a table has multiple AFTER triggers, then you can specify which trigger should be executed first and which trigger should be executed last using the stored procedure sp_settriggerorder.

Question 29.
What is SQL injection?
Answer:
It is a Form of attack on a database-driven Website in which the attacker executes unauthorized SQL commands by taking advantage of insecure code on a system connected to the Internet, bypassing the firewall. SQL injection attacks are used to steal information from a database from which the data would normally not be available and/or to gain access to an organization’s host computers through the computer that is hosting the database.

SQL injection attacks typically are easy to avoid by ensuring that a system has strong input validation. As name suggest we inject SQL which can be relatively dangerous for the database. For example, this is a simple SQL

SELECT email, passwd, login_id, full_name 
FROM members 
WHERE email = 'x'

Now somebody does not put “x” as the input but puts “x ; DROP TABLE members;”. So the actual SQL which will execute is:

SELECT email, passwd, login_id, full_name
FROM members -
WHERE email = 'x'; DROP TABLE members;

Think what will happen to your database.

Question 30.
What is the difference between Stored Procedure and User-Defined Function?
Answer:
Following are some major differences between a Stored Procedure (SP) and User-Defined Functions (UDF):

  • The main purpose of UDF was to increase reuse in the stored procedures. So you can call UDF from – a stored procedure and not vice versa.
  • You cannot change any data using UDF while you can do everything with a stored procedure.
  • UDF does not return output parameters while SP’s returns output parameters.
Note: SQL Server product is equivalently important from an interview point of view. I have dedicated a complete
 book “SQL Server Interview questions” to crack SQL Server. If you are interested in buying the book mail 
bpb@bol.net.in /bpb@vsnl.com or call the nearest BPB bookstall for my book. For shop phone numbers 
you can either see the back or front page of the book.

Angular Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Angular

Question 1.
What is Angular JS?
Answer:
“AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML Ul elements.”
Let us try to understand the above definition with simple sample code.
Below is a simple “Customer” function with the “CustomerName” property. We have also created an object called “Cust” which is of the “Customer” class type.

function Customer( )
{
    this.CustomerName = "Angularlnterview";
}
var Cust = new Customer( );

Now let us say the above customer object we want to bind to a HTML textbox called as “Txtcus tomerName”. In other words when we change something in the HTML textbox the customer object should get updated and when something is changed internally in the customer object the Ul should get updated.

<input type=text id=’TxtCustomerName” onchange=”UitoObject( )”/>

So in order to achieve this communication between Ul to object developers end up writing functions as shown below. “UitoOb j ect” function takes data from Ul and sets it to the object while the other function “Obj ecttoui” takes data from the object and sets it to Ul.

function UitoObject( )
{
      Cust.CustomerName = $("#TxtCustomerName").val( );
}
function ObjecttoUi( )
{
     $("#TxtCustomerName").val(Cust.CustomerName);
}

So if we analyze the above code visually it looks something as shown in Figure 8.1. Your both functions are nothing but binding code logic which transfers data from Ul to object and vice versa.

Angular Interview Questions in . NET chapter 8 img 1

Now the same above code can be written in Angular as shown below. The JavaScript class is attached to a HTML parent div tag using “ng-controller” directive and the properties are bonded directly to the text box using “ng-model” declarative.

So now whatever you type in the textbox updates the “Customer” object and when the “Customer” object gets updated it also updates the Ul.

<div ng-controller="Customer">
<input type=text id="txtCustomerName" ng-model="CustomerName"/>
</div>

in short if you now analyze the above code visually you end up with something as shown in the below Figure 8.2. You have the VIEW which is in HTML, your MODEL objects which are javascript functions and the binding code in Angular.

Angular Interview Questions in . NET chapter 8 img 2

Now that binding code have different vocabularies.

  • Some developers called it “ViewModel” because it connects the “Model” and the “View”.
  • Some called it “Presenter” because this logic is nothing but presentation logic.
  • Some termed it as “Controller” because it controls how the view and the model will communicate.

To avoid this vocabulary confusion Angular team has termed this code as “WHATEVER”. It’s that “WHATEVER” code which binds the Ul and the Model. That’s why you will hear lot of developers saying Angular implements “MVW” architecture.

Question 2.
Explain directives in Angular.
Answer:
Directives are attributes decorated on the HTML elements. All directives start with the word “ng”. As the name says directive it directs Angular what to do.

For example below is a simple “ng-model” directive which tells angular that the HTML textbox ” txtCus tomerName ” has to be binded with the “CustomerName” property.

<input type=text id=”txtCustomerName” ng-modei=”CustomerName”/>

Some of the most commonly used directives are ng-app, ng-controller and ng-repeat.

Question 3.
What are controllers and need of ng-controller and ng-model in Angular?
Answer:
“Controllers” are simple JavaScript function which provides data and logic to HTML Ul as shown in Figure 8.3. As the name says controller they control how data flows from the server to HTML Ul.

Angular Interview Questions in . NET chapter 8 img 3

For example below is simple “Customer” controller which provides data via “CustomerName” and “CustomerCode” properties and Add/ Update logic to save the data to database.

Note: Do not worry too much about the $ scope, we will discuss the same in the next question.
function Customer($scope)
{
      $scope.CustomerName = "Shiv";
      $scope.CustomerCode = "1001";
      $scope.Add = function ( ) {
      }
      $scope.Update = function ( )
      }
}

“ng-controller” is a directive. Controllers are attached to the HTML Ul by using the “ng-controller” directive tag and the properties of the controller are attached by using “ng-model” directive. For example, below is a simple HTML Ul which is attached to the “Customer” controller via the “ng-controller” directive and the properties are bonded using “ng-model” directive.

<div ng-controller="Customer">
<input type=text id="Cust:omerName" ng-model= "CustomerName"/xbr />
<input type=text id="CustomerCode" ng-model="CustomerCode"/>
</div>

Question 4.
What are expressions in Angular?
Answer:
Angular expressions are unit of code which resolves to value. This code is written inside curly braces “{ }”
Below are some examples of angular expressions:
The below expression adds two constant values.

{{1+1}}

The below expression multiplies quantity and cost to get the total value.

The value total cost is {{ quantity * cost}}

The below expression displays a controller scoped variable.

<divng-controller=”CustomerVM”>

The value of Customer code is {{CustomerCode}}

<div ng-controller="CustomerVM">
         The value of Customer code is {{CustomerCode}}
</div>

Question 5.
How can we initialize Angular application data?
Answer:
We can use the “ng-init” directive to achieve the same. You can see in the below example we have used the “ng-init” directive to initialize the “pi” value.

<body ng-app="myApp" ng-init="pi=3.14">
           The value of pi is {{pi}}
</body>

Question 6.
Explain $scope in Angular?
Answer:
“$scope” is an object instance of a controller. “$scope” object instance get’s created when the “ng- controller” directive is encountered.
For example in the below code snippet we have two controllers “Function1” and “Function2”. In both the controllers we have a “ControlierName” variable.

function Function1($scope)
{
     $scope.ControllerName = "Function1";
}
function Function2($scope)
{
    $scope.ControlierName = "Function2";
}

Now to attach the above controllers to HTML Ul we need to use the “ng-controller” directive. For instance, you can see in the below code snippet how the “ng-controller” directive attaches “Function1” with the “div1” tag and “Function2” with the “div2” tag.

<div id="div1" ng-controller="Function1">
       Instance of {{ControlierName}} created
</div>
<div id="div2" ng-controller="Function2">
      Instance of {{ControlierName}} created
</div>

So this is what happens internally. Once the HTML DOM is created Angular parser starts running on the DOM as shown in Figure 8.4 and following are the sequence of events:

  • The parser first finds “ng-controller” directive which is pointing to “Function1”. It creates a new instance of “$scope” object and connects to the “div1 ” LJI.
  • The parser then starts moving ahead and encounters one more “ng-controller” directive which is pointing to “Function2”. It creates a new instance of “$scope” object and connects to the “div2” Ul.

Angular Interview Questions in . NET chapter 8 img 4

Now once the instances are created, below is a graphical representation of the same. So the “Divi” HTML Ul is binded with “Functionl” $scope instance and the “Div2” HTML Ul is binded with “Function2” $scope instance as shown in Figure 8.5. In other words now anything changes in the $scope object the Ul will be updated and any change in the Ul will update the respective $scope object.

Angular Interview Questions in . NET chapter 8 img 5

Question 7.
What is “$rootScope” and how is it related with “$scope”?
Answer:
“$rootScope” is a parent object of all “$scope” angular objects created in a Web page as shown in Figure 8.6.

Angular Interview Questions in . NET chapter 8 img 6

Let us understand how Angular does the same internally. Figure 8.7 shows a simple Angular code which has multiple “Div” tags and every tag is attached to a controller. So let us understand step-by-step how angular will parse this and how the “$rootScope” and “$scope” hierarchy is created.

Angular Interview Questions in . NET chapter 8 img 7

The Browser first loads the above HTML page and creates a DOM (Document Object Model) and Angular runs over the DOM. Below are the steps how Angular creates the root scope and scope objects.

• Step 1: Angular parser first encounters the “ng-app” directive and creates a “$rootScope” object in memory.

• Step 2: Angular parser moves ahead and finds the expression {{Somevalue}}. It creates a variable from the expression and attaches this variable to the “$rootScope” object created in Step 1.

• Step 3: Parser then finds the first “div” tag with “ng-controller” directive which is pointing to “Function1” controller. Looking at the “ng-controller” directive it creates a “$scope” object instance for “Function1” controller. This object is then attached to the “$rootscope” object.

• Step 4: Step 3 is then repeated by the parser every time it finds a “ng-controller” directive tag. Step 5 and Step 6 is the repetition of Step 3.

If you want to test the above fundamentals you can run the below sample Angular code. In the below sample code we have created controllers “Function1” and “Function2”. We have two counter variables one at the root scope level and other at the local controller level.

<script language=javascript>
function Functioni($scope, $rootScope)
{
       $rootScope.Counter = (($rootScope.Counter || 0) + 1);
       $scope.Counter = $rootScope.Counter;
       $scope.ControllerName = "Function1";
}
function Function2 ($scope, $rootscope)
{
      $rootScope.Counter = (($rootScope.Counter || 0) + 1);
      $scope.ControllerName = "Function2";
}
var app = angular.module("myApp", [ ]); // creating a APP
app.controller("Functionl", Functionl); // Registering the VM
app.controller("Function2", Function2);

</script>

Below is the HTML code for the same. You can we have attached “Functionl” and “Function2 ” two times with ”ng-controller” which means four instances will be created.

<body ng-app="myApp" id=1>
Global value is {{Counter}}<br />
<div ng-controller="Function1">
Child Instance of {{ControllerName}} created: {{Counter}]
</div><br />
<div ng-controller="Function2">
Child Instance of {{ControllerName}} created: {{Counter}}
</div><br />
<div ng-controller="Function1">
Child Instance of {{ControllerName}} created: {{Counter}}
</div><br />
<div ng-controller="Function2">
Child Instance of {{ControllerName}} created: {{Counter}}
</div><br />
</body>

Figure 8.8 the output of the code you can see the global variable of root scope has be incremented four times because four instances of $scope have been created inside “$rootscope” object.

Angular Interview Questions in . NET chapter 8 img 8

Question 8.
Do I need jQuery for Angular?
Answer:
No, you do not need jQuery for Angular. It’s independent of jQuery.

Question 9.
How is the data binding in Angular?
Answer:
Its two-way binding. So whenever you make changes in one entity the other entity also gets

Global value is 4
Child Instance of Function1 created 1 Child Instance of Functio1 created 4 Child Instance of Function1 created 3 Child Instance of Function2 created

Question 10.
Explain compile and link phase.
Answer:
Angular framework is a parser. A parser which parses the Angular directives and render’s HTML output. Angular parser works in three steps:
Step 1: HTML browser parses the HTML and creates a DOM (Document Object Model).
Step 2: Angular framework runs over this DOM looks at the Angular directives and manipulates the DOM accordingly.
Step 3: This manipulated is then rendered as HTML in the browser

Angular Interview Questions in . NET chapter 8 img 9

Now the above angular parsing is not so simple as it looks to be. It occurs in two phases “Compile” and “Link” as shown in Figure 8.9. First the Compile phase executes followed by the Link phase as shown in Figure 8.10. Fl9ure 8.10: Compile Phase

Angular Interview Questions in . NET chapter 8 img 10

In compile phase the angular parser starts parsing the DOM and whenever the parser encounters a directive it create a function. These functions are termed as template or compiled functions. In this phase we do not have access to the $ scope data.
In the link phase the data, i.e., ($scope) is attached to the template function and executed to get the final HTML output as shown in Figure 8.11.

Angular Interview Questions in . NET chapter 8 img 11

Question 11.
How do we make HTTP get and post calls in Angular?
Answer:
To make HTTP calls we need to use the ” $HTTP ” service of Angular. In order to use the HTTP services you need to make provide the “$HTTP” as a input in your function parameters as shown in the below code.

function CustomerController($scope, $HTTP)
{
       $scope.Add = function( )
       {
           $HTTP({ method: "GET", url: "HTTP: //localhost: 8438/SomeMethod"
           }).success(function (data, status, headers, config)
           {
                // Here goes code after success
           }
      }
}

“$HTTP” service API (Application Programming Interface) needs at least three things:

  • First, what is the kind of call “POST” or “GET”.
  • Second is the resource URL on which the action should happen.
  • Third we need to define the “success” function which will be executed once we get the response from the server.
$HTTP({ method: "GET", url: "HTTP: //localhost: 8438/SomeMethod"
}).success(function (data, status, headers, config)
{
     // Here goes code after success
}

Question 12.
How do we pass data using HTTP POST in Angular?
Answer:
You need to pass data using the “data” keyword in the “$HTTP” service API function. In the below code you can see we have created a JavaScript object “myData” with “CustomerName” property. This object is passed in the “$HTTP” function using HTTP POST method.

Var myData = { };
myData.CustomerName = "Test";
$HTTP({ method: "POST",
     data: myData,
     url: "HTTP: //www.xyz.com"})
     .success(function (data, status, headers, config)
     {
        // Here goes'code after success
}

Question 13.
What is dependency injection and how does it work in Angular?
Answer:
Dependency Injection (Dl) is a process where we inject the dependent objects rather than consumer creating the objects. Dl is everywhere in Angular or we can go one step ahead and say Angular cannot work without Dl.
For example, in the below code “$scope” and “$HTTP” objects are created and injected by the angular framework. The consumer, i.e., “CustomerController” does not create these objects himself/herself rather Angular injects these objects.

function customercontroller ($scope, $HTTP)
{
     // your consumer would be using the scope and HTTP objects
}

Question 14.
How does Dl get benefits in Angular?
Answer:
There are two big benefits of Dl: Decoupling and Testing.
Let’s first start with Decoupling. Consider your application has a logger functionality that helps to log errors, warnings, etc., in some central place. This central place can be a file, event viewer, database, etc.

function FileLogger( )
{
this.Log = function ( ) {
alert("File logger");
} ;
}
function EventLogger( )
{
this.Log = function ( ) {
alert("Event viewer logger");
} ;
}

Now let’s say you have a “Customer” class that wants to use the “Logger” classes as shown in Figure 8.12. Now which “Logger” class to be used depends on configuration.

Angular Interview Questions in . NET chapter 8 img 12

So the code of “Customer” is something as shown below. So depending on the configuration “Customer” class either creates “FileLogger” or it creates the “EventLogger” object.

function Customer($scope, Logger)
{
      $scope.Logger = { };
      if (config.Loggertype = "File")
      {
           $scope.Logger = new FileLogger( );
      }
      else
      {
          $scope.Logger = new EventLogger( );
      }
}

But with Dl our code becomes something as shown below. The “Customer” class says it is not worried from where the “Logger” object comes and which type of “Logger” objects are needed. This classes just uses the “Logger” object.

function customer ($scope, $HTTP, Logger)\
{
     $ scope.Logger = Logger;
}

With this approach when a new “Logger” object gets added the “Customer” class does not have to worry about the new changes because the dependent objects are injected by some other system.

The second benefit of Dl is testing. Let’s say you want to test the “Customer” class and you do not have an Internet connection. So your “$HTTP” object method calls can throw errors. But now you can mock a fake * $HTTP” object and run your Customer class offline without errors. The fake object is injected using Dl.

Question 15.
What are services in Angular?
Answer:
Service helps to implement dependency injection. For instance, let’s say we have the below “Customer” Class that needs the “Logger” object. Now “Logger” object can be Of “FileLogger” type or”EventLogger ‘ type-

function Customer($scope, $HTTP, Logger)
{
        $scope.Logger = Logger;
}

So you can use the “service” method of the application and tie up the “EventLogger” object with the “Logger” input parameter of the “Customer” class.

var app = angular.module("myApp", [ ]); // creating a APP
app.controller("Customer", Customer); // Registering the VM
app.service("Logger", EventLogger); // Injects a global Event logger object

So when the controller object is created the “EventLogger” object is injected automatically in the controller class.

Question 16.
Are Service object instances global or local?
Answer:
Angular Services create and inject global instances. For example below is a simple “Hitcounter” class which has a “Hit” function and this function increments the variable count internally every time you call hit the button.

function HitCounter( )
{
      var i = 0;
      this.Hit = function ( )
      {
           i + +;
           alert(i);
      };
}

This “Hitcounter” class object is injected in the “Myciass” class as shown in the below code.

function MyClass($scope, Hitcounter)
{
$scope.HitCounter = HitCounter;
}

The below code advises the Angular framework to inject the “Hitcounter” class instance in the “Myciass” class. Read the last line of the below code especially which says to inject the “Hitcounter” instance.

var app = angular.module("myApp", [ ]); // creating a APP
app.controller("MyClass", MyClass); // Registering the VM
app.service("Hitcounter", Hitcounter); // Injects the object

Now let’s say that the “Controller” “MyClass” is attached to two div tags as shown in Figure 8.13.
So two instances of “MyClass” will be created. When the first instance of “MyClass” is created a “Hitcounter” object instance is created and injected into the “MyClass” first instance.
When the second instance of “MyClass” is created the same “Hitcounter” object instance is injected into the second instance of “MyClass”.
Again I repeat the same instance is injected into the second instance, new instances are not created.

Angular Interview Questions in . NET chapter 8 img 13

If you execute the above code you will see counter values getting incremented even if you are coming through different controller instances.

Question 17.
What is a Factory in Angular?
Answer:
“Factory” in real-world means a premise where products are manufactured. Let’s take an example of a computer manufacturing firm. Now the company produces different kinds and sizes of computers like laptops, desktops, tablets, etc.

Now the process of manufacturing the computer products is are same with slight variation. To manufacture any computer we need a processor, RAM (Random Access Memory), and hard disk. But depending on what kind of final case packing is the final product shapes.

Angular Interview Questions in . NET chapter 8 img 14

Angular as shown in Figure 8.14.
For example see the below code we have a “Customer”, “Phone” and “Address” class.

function Customer( )
{
      this.CustomerCode = "1001";
      this.CustomerName = "Shiv";
}
function Phone( )
{
     this.PhoneNumber = " ";
}
function Address ( )
{
     this.Address1 = " ";
     this.Address2 =" ";
}

 

So now we would create different types of “Customer” object types using the combination of
“Address” and “Phones” object.

  • We would like to combine “Customer” with “Address” and create a “Customer” object which has the “Address” collection inside it.
  • Or must be we would like to create a “Customer” object with “Phone” objects inside it.
  • Or must be a “Customer” object with both “Phone” and “Address” objects.

Angular Interview Questions in . NET chapter 8 img 15

In other words, we would like to have different permutations and combinations to create different types of “Customer” objects.
So let’s start from the bottom. Let’s create two factory functions one which creates the “Address” object and the other which creates “Phone” objects.

function CreateAddress( )
{
      var add = new Address( );
      return add;
}
function CreatePhone( )
{
      var phone = new Phone( );
      return phone;
}

Now let’s create a main factory function that uses the above two small factory functions and gives us all the necessary permutations and combinations.
In the below factory you can see we have three functions:

  • “CreateWithAddress” creates “Customer” with “Address” objects inside it.
  • “CreateWithPhone” creates a “Customer” object with “Phone” objects inside it.
  • “CreateWithPhoneAddress” creates “Customer” Object with aggregated “Phone” and “Address” objects.
function CreateCustomer( )
{
      return
      {
           CreateWithAddress: function ( )
           {
               var cust = new Customer();
               cust.Address = CreateAddress( );
               return cust;
          },
          CreateWithPhone: function ( )
          {
              var cust = new Customer( );
              cust.Phone = { };
              cust.Phone = CreatePhone( );
              return cust;
         }
         CreateWithPhoneAddress: function ( )
         {
             debugger;
             var cust = new Customer( );
             cust.Phone = CreatePhone( );
             cust.Address = CreateAddress( );
             return cust;
        }
     }
}

Below is a simple “CustomerController” which takes “CustomerFactory” as the input. Depending on “TypeOfCustomer” it creates with “Address”, “Phones” or both of them.

function CustomerController($scope, Customerfactory)
{
     $scope.Customer = { };
     $scope.Init = function(TypeofCustomer)
     {
           if (TypeofCustomer == "1")
           {
               $scope.Customer = Customerfactory.CreateWithAddress( );
           }
           if (TypeofCustomer == "2")
           {
               $scope.Customer = Customerfactory.CreateWithPhone( );
           }
           if (TypeofCustomer == "3")
           {
               $scope.Customer =
               Customerfactory.CreateWithPhoneAddress( ) ;
           }
     }
}

You also need to tell Angular that the “CreateCustomer” method needs to be passed in the input. For that, we need to call the “Factory” method and map the “CreateCustomer” method with the input parameter “CustomerFactory” for dependency injection.

var app = angular .module ( "myApp" , [ ]) ; // creating a APP
app.controller("CustomerController", CustomerController); // Register the VM
app.factory("Customerfactory", CreateCustomer);

So if we consume the “CustomerControiier” in Ul, depending on the situation it creates different flavors of the “Customer” object. You can see in Figure 8.16 we have three different “div” tags and depending on the “Typeofcustomer” we are displaying data.

Angular Interview Questions in . NET chapter 8 img 16

Question 18.
What is the difference between Factory and Service?
Answer:
“Factory” and “Service” are different ways of doing Dl (Dependency Injection) in angular. Please read the previous question to understand what is Dl.
So when we define Dl using “service” as shown in the code below. This creates a new global instance of the “Logger” object and injects it into the function.

app. service (“Logger"’, Logger); //Injects a global object

When you define Dl using a ” factory” it does not create an instance. It just passes the method and later the consumer internally has to make calls to the factory for object instances.

app. factory(“Customertactory”, CreateCustomer);

Figure 8.17 depicts visually how Dl process for “Service” is different than “Factory”

Angular Interview Questions in . NET chapter 8 img 17

Factory Service
Usage When we want to create different types of objects

depending on scenarios. For example, depending

on scenario we want to create a simple “Customer”

object, or “Customer” with “Address” object or

“Customer” with “Phone” object. See the previous

question for more detailed understanding.

When we have utility or shared functions to be injected like Utility, Logger, Error handler, etc.
Instance No Instance created. A method pointer is passed. Global and Shared instance is created.

 

Question 19.
How are validations implemented in Angular?
Answer:
Angular leverages HTML 5 validation attributes and new HTML 5 form element types to implement validation as shown in Figure 8.18.

Angular Interview Questions in . NET chapter 8 img 18

For instance below is a simple form which has two textboxes. We have used HTML 5 “required” validation attribute and a form element of type “email”.

<form name="frml" id="frml" >
Name: <input type=text name="CustomerName"
id="CustomerName" required /> Email: <input type=email name="Email" id="Email" />
<input type=submit value="Click here"/>
</form>

Below are some example of new form elements introduced in HTML 5 and Angular works with almost all of them:

  • Color.
  • Date
  • Datetime-local
  • E-mail
  • Time
  • URL
  • Range
  • Telephone
  • Number
  • Search

When you run the above HTML inside a browser which understands HTML 5, you will see your validations and form types in actions as shown in the Figure 8.19.

Angular Interview Questions in . NET chapter 8 img 19

Angular leverages HTML 5 validation attributes and new HTML 5 form elements. Now if we Click here want Angular to handle validation we need HTML 5 to do validation. So for that the first Figure 8.19: Validation and Form Types step is to specify “novalidate” attribute on the form tag.

<form name="frml" novalidate>
</form>

So now the HTML will not fire those validations it will be routed to the Angular engine to further take actions.
In other words when end user fills data in the HTML Ul, validation events are routed to Angular framework and depending on scenario Angular sets a field called as “$valid”. So if the validations are fine it sets it to “True” or else its sets it to “False” as shown in Figure 8.20.

Angular Interview Questions in . NET chapter 8 img 20

So you can see in the below code we have attached the angular controller and models to the text boxes. Watch the code of the button it has “ng-disabied” attribute which is set via the “$vaiid” property in a negated fashion.

Negated fashion means when there is no error it should enable the button and when there are errors that means it is false it should disable the button.

<form name="frml" novalidate>
Name: <input type=text ng-model="Customer.CustomerName" name="CustomerName" required />
Email: <input type=email ng-model="Customer.Email" name="Email" />
<input type=submit value="Click here" ng-disabled="!(frml.$valid)"/>
</form>
Note: “Name” is needed for the validations to work.

Question 20.
How to check error validation for a specific field?
Answer:
To check for a specific field you need to use the below DOM code.

!frm1.CustomerName.$valid

Question 21.
What does SPA (Single Page Application) mean?
Answer:
SPA is a concept where rather loading pages from the server by doing postbacks we create a single shell page or master page and load the Web pages inside that master page.

Question 22.
How can we implement SPA with Angular?
Answer:
By using Angular routes.

Question 23.
How to implement routing in Angular?
Answer:
Implementing Angular route is a five-step process:
Step 1: Add the “angular-route.js” file to your view.

<script src=”~/Scripts/angular-route.js”x/script>

Step 2: Inject “ngRoute” functionality while creating Angular app object.

varapp = angular.module(“myApp”, [‘ngRoute’]);

Step 3: Configure the route provider.
In route provider we need to define which URL pattern will load which view. For instance in the below code we are saying “Home” loads “Yoursite/Home” view and “Search” loads “YourSite/ Search” view.

app.config(['$routeProvider',
    function ($routeProvider) {;
          $routeProvider.
          when('/Home, {
                templateUrl: 'Yoursite/Home',
                controller: 'HomeController'
          }) .
          when('/Search', {
                templateUrl: YourSite/Search',
                controller: 'SearchController'
         }) .
         otherwise({
               redirectTo: '/'
        });
}]);

Step 4: Define hyperlinks.
Define hyperlink with the ” #” structure as shown below. So now when user clicks on the below anchor hyperlinks, these actions are forwarded to route provider and router provider loads the view accordingly.

<div>
<a href="#/Home">Home</axbr /> .
<a href="#/Search"> Search </a><br />
</div>

Step 5: Define sections where to load the view.
Once the action comes to the router provider it needs a place holder to load views. That’s defined by using the “ng-view” tag on a HTML element. You can see in the below code we have created a “Div” tag with a place holder. So the view will load in this section.

<divng-view>
</div>

So if we summarize angular routing is a three-step process. Figure 8.21 shows a visual diagram for the same.

  • Step 1: End user clicks on a hyperlink or button and generates action.
  • Step 2: This action is routed to the route provider.
  • Step 3: The router provider scans the URL (Uniform Resource Locator) and loads the view in the place holder defined by “ng-view” attribute.

Angular Interview Questions in . NET chapter 8 img 21

Question 24.
How can we create a custom directive in Angular?
Answer:
Till now we have looked in to pre-defined Angular directives like “ng-controller”, “ng-model” and so on. But what if we want to create our own custom Angular directive and attach it with HTML elements as shown in the below code.

<divid=footercompany-copy-right></div>

To create a custom directive we need to use the “directive” function to register the directive with angular application. When we call the “register” method of “directive” we need to specify the function which will provide the logic for that directive.
For example, in the below code we have created a copyright directive and it returns a copyright text. Please note “app ” is an Angular application object which has been explained in the previous sections.

app.directive('companyCopyRight', function ( )
{
      return
      {
          template: '@CopyRight questpond.com '
     };
}) ;

The above custom directive can be later used in elements as shown below code.

<div ng-controller="CustomerViewModel">
<div company-Copy-rightx/div>
</div>

Question 25.
What kind of naming conventions is used for custom directives?
Answer:
For angular custom directive the best practice is to follow camel casing and that also with at least two letter’s. In camel case naming convention we start with a small letter, followed by a capital letter for every word.

Some example of camel cases are “loopCounter”, “isValid” and so on. .

So when you register a custom directive it should be with camel case format as shown in the below code “companyCopyRight” and in the Figure 8.22 as well.

app.directive('companyCopyRight', function ( )
{
       return
       {
             template: '@CopyRight questpond.com '
       };
});

Later when this directive is consumed inside HTML before each capital letter of camel case we need to insert a as specified in the below code.

<div company-copy-rightx/div>

If you are making a one letter prefix like “copyright” it is very much possible that tomorrow if HTML team creates a tag with the same name, it will clash with your custom directive. That’s why angular team recommends camel case which inserts a in between to avoid further collision with future HTML tags.

Angular Interview Questions in . NET chapter 8 img 22

Question 26.
What are the different custom directive types in Angular JavaScript?
Answer:
There are different flavors of Angular directives depending till what level you want to restrict your custom directive.
In other words do you want your custom directive to be applied only on HTML element or only on an attribute or just to CSS (Cascading Style Sheet), etc.
So in all there are four different kinds of custom directives:

  • Element directives (E)
  • Attribute directives (A)
  • CSS class directives (C)
  • Comment directives (M)

Below is a simple custom directive implementation at the element level.

myapp.directive('userinfo', function()
{
         var directive = { };
         directive.restrict = 'E';
         directive.template = "User: {{user.firstName}} {{user.lastName}}";
         return directie;
}) ;

The “restrict” property is set to “E” which means that this directive can only be used at element level as shown in the code snippet below.

<userinfox/userinfo>

If you try to use it at an attribute level as shown in the below code it will not work.

<div userinfox/div>

So “E” for element, “A” for attribute, “C” for CSS and “M” for comments.

Question 27.
What if I want custom directives to be applied on element as well as attributes?
Answer:

directive.restrict = ‘EA’;

Question 28.
Can I set an Angular directive template to a HTML Web page?
Answer:
Yes, you can set template to page directly by using “tempiateUri” property of the directive as shown in the code snippet below.

directive.templateUrl = “/templates/footer.html”;

Some more questions of Angular for home work.

What is the need of $.Watch?
What is the difference between $HTTP and $resource?
What are promises in Angular?

JQUERY Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on JQUERY

Question 1.
What is jQuery?
Answer:
jQuery is a reusable JavaScript library which simplifies JavaScriptcoding. So rather than writing lengthy JavaScript code as shown below you can use jQuery.

document.getElementByld(“txt1”).value = “hello”;

By jQuery the above JavaScript code is now simplified as shown below.

$(“#txt 1 ”). val(“Hello”);

Question 2.
So will jQuery replace JavaScript?
Answer:
No, jQuery is not meant to replace JavaScript. jQuery is a library while JavaScript is a language. jQuery sits on the top of JavaScript to make your development easy.

Question 3.
So how do we use these reusable jQuery libraries?
Answer:
You need to download jQuery.js file from jQuery.com and include the same in your Web pages. The jQuery files are named with version number like “jQuery-1.4.1.js” where 1.4.1 is the version of the JavaScript file. So at the top of your Web page you need to include the JavaScript as shown in the below code.

<script src-”Scripts/jQuery-1.4.1.min.js” type-”text/javascript”x/script>

Question 4.
What is CDN (Content Delivery Network)?
Answer:
In CDN multiple copies of the Website is copied on different geographical servers. When users send request for Website content which have CDN-enabled depending on their geographical location, content is served from the nearest geographical location server to the user.

JQUERY Interview Questions in . NET chapter 7 img 1

So if a user is from India, the Indian CDN server will serve request for Indian users. This leads to faster delivery of data.

Question 5.
For jQuery files which are the popular CDN’s?
Answer:
There are two popular CDN’s: Microsoft and Google.

If you want to reference Google CDN JQuery files you can use the below script.

<script type="text/javascript" .
src=''HTTP : //ajax, googleapis . com/aj ax/libs/jQuery/1.9.1/ j Query.min.j s " >
</script>

If you want to use Microsoft CDN you can use the below JavaScript.

<script type="text/javascript"
src="HTTP: //ajax.microsoft.com/ajax/jQuery/jQuery-1.9.1.min.j s">
</script>

Question 6.
How can we reference local jQuery files if CDN fails?
Answer:
Many times it is possible that Microsoft and Google servers can go down for some time. So in those situations you would like your page to reference jQuery files from local server.
So to implement a CDN fallback is a two-step process:
First reference is the CDN jQuery. In the below code you can see we have reference Microsoft CDN jQuery file.

HTTP: //ajax, microsoft. com/ajax/jQuery/jQuery-1.9.1. min.js “></script>

Now if Microsoft CDN is down then the jQuery value will be “undefined”. So you can see in the below code we are checking if the jQuery is having “undefined” value then do a document write and reference your local jQuery files.

if (typeof jQuery == 'undefined')
{
document.write(unescape("%3Cscript src='Scripts/jQuery.1.9.1.min.js' type='text/javascript'%3E%3C/script%3E"));
}

Below is the full code for the same.

<script type="text/javascript" src=" HTTP: //ajax.microsoft.com/ajax/jQuery/ jQuery-1.9.1.min.js "></script>
<script type=''text/javascript">
if (typeof jQuery == 'undefined')
{
document.write(unescape(”%3Cscript src='Scripts/jQuery.1.9.1.min.js'
type='text/javascript'%3E%3C/script%3E")); v
}
</script>

Question 7.
What is the difference between jQuery.js and jQuery.min.js file?
Answer:
First thing both the files provide the same jQuery functionalities. One is a long version and the other is compressed/minified version. The minified version is compressed to save bandwidth and space by compressing, and removing all the white spaces. Figure 7.2 shows the view of jQuery.js.

(function( window, undefined ) {

// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init a return
new jQuery.fn.init( selector, context );
};
// Map over jQuery in case of overwrite
JQuery = window. jQuery,
// Map over the $ in case of overwrite
_$ = window.$,

Figure 7,3 shows the view of jQuery.min.js file (compressed and minified).

* Date: Mon 3 an 25 19:43:33 2010 -0500
*/
(function(z,vj{function la(){if(!c,isReady){try{r.dotuwentElement.doScroll e(a[0],b)multifunction 
3(){return(new Date).getTime()}function Y(){returr a.currentTarget);m=0;for(s»i.length;sjm++)for(o in x)
{j=x[o];n=i[m].elefl lljfunction qa(a,b){var d=0;b.each(function(){if(this.nodeHa«e===(a[d]&&aj c.clean
(a,b,f,d)}if(e)c.fragments[a[0]]=i?f:l;return{fragment:f,cacheable: va»false,P=[],L,$=Obj ect.prototype.toSt 
ring,a a=Obj ect.prototype.ha sOwnProf [f ]) ja=(a.cacheable?a.fragment.cloneNode(true):a.fragment).
childNodes}}el: this)},selector:"'Jquery:"1,4.1”,length:0,size:function(){return this.ler a,b)},ready:function(a)
{c.bindReady();if(c,isReady)a.call(r,c);else P&SP.f c.fn.init,prototype=c.fnj c.extend=c.fn.extend-function()
{var a=arguments[( Oa;if(a)z.JQuery=Naireturn c},isReady:false,ready:function(){if(ic.isReadj c.ready).;var
 a=false|try{a=z.fraMeEle«ent==mill}c3tch(b){}r.docu*enfElemer
Figure 7.3: Compressed and Minified

Question 8.
When should we use jQuery.js over jQuery.min.js?
Answer:
When you are doing development use “jQuery.js” file because you would like to debug the JavaScript code, etc. Use “jQuery.min.js” for production environment. In production / live environment we would like to consume less bandwidth, we would like to our pages to load faster. .

Question 9.
What is the use jQuery.vsdoc.js?
Answer:
This file you can include if you want to enable Intellisense in Visual Studio for jQuery as shown in Figure 7.4.

JQUERY Interview Questions in . NET chapter 7 img 2

Question 10.
How does the basic syntax of JQuery looks like?
Answer:
jQuery syntax structure can be broken down into four parts:

JQUERY Interview Questions in . NET chapter 7 img 3

All JQuery commands start with a “$” sign as shown in Figure 7.5.

  • Followed by the selection of the FITML element. For example below is a simple image where we are selecting a HTML textbox by id “txt1 ”.

Then followed by the dot (.) separator. This operator will separate the element and the action on the element.

  • Finally what action you want to perform Figure 7.5: Basic Syntax
    on the HTML element. For instance in the below jQuery code we are setting the text value to “Hello jQuery’.

Question 11.
What is the “$” sign in jQuery?
Answer:
The “$” sign is an alias for jQuery.

Question 12.
When should we use jQuery.noConflictQ?
Answer:
There are many JavaScript frameworks like MooTools, Backbone, Sammy, Cappuccino, Knockout, etc. Some of these frameworks also use “$” sign so this can lead to conflict with jQuery framework.
So you can use the “noConflict” method and release the jQuery “$” sign as shown in the below code.

$.noConflict();
jQuery(“p”).text(“i am jQuery and I am working... ”);

You can also create your own jQuery shortcut as shown below.

var jq = $.noConflict();
jq(“p”). text(“l am invoked using jQuery shortcut... ”);

Question 13.
What are the different ways by which you can select a HTML element in jQuery?
Answer:
You can select jQuery elements in the following ways:
Select all: Below is a simple code snippet which selects all elements and hides them.

$(“*”). hide( );

Select by ID: If your HTML elements have id’s like the below HTML code andyou want to select the same by id.

<p id="p 1 ">Some Para</p>

Below is how the jQuery code by ID selection code would look like.

$(“#p1”).hide();

Select by class: If your HTML element has class names and you want to select them in jQuery then you need to use the dot operator followed by the classname as shown in the below code.

<p class=”class1 ">Some Para</p> $(“.class1”).hide()

Select by class and element: Consider the below HTML code where we have elements with “class’
names.

<p class="cl">para 1</P>
<P class="cl">para 2</p>
<P class="c2">para 2</p>
<P class="c2">para 2</p>

So if you wish to select by “element” and “class” in jQuery your selector code becomes something as below.

$(“p.c1”).hide();

Select using Equal method
Select using Find method
Select using Filter method

Question 14.
What is the use of document.ready in jQuery?
Answer:
“document. ready” event occurs once the complete HTML DOM is loaded. So the next question is when do we actually need this event?. Consider the below simple code where we are trying to set a text box “textl” with value “Sometext”.
Now at the point when JQuery code tries set the textbox value, at that moment that text bcx is not available in the HTML DOM (Document Object Model). So it throws an exception for the same.

<script>
$("#textl").val("Sometext"); // Throws exception as the textbox is not //accessible at‘ this moment
</script>
</head>
<body>
<input type="text" id="textl11 />
</body>

So we would like to execute the JQuery code which sets the textbox value only when all the HTML objects are loaded in DOM. So you can replace the code of setting text box value to something as shown below.

<script>
$(document).ready(function(){
$("#textl").val("Sometext");
}) ;
</script>

Question 15.
Can we have two document. ready in a Web page?
Answer:
Yes.

Question 16.
How can we attach a method to a HTML element event using jQuery?
Answer:
Below is a simple code which attaches a function to click event of a button.

$("button").click(function(){
$("p").toggle();
}) ;

Below is one more example where we have attached the function to a mouseenter event of a paragraph.

$("#pl").mouseenter(function(){
alert("You entered pi!");
}) ;

Question 17.
How can we add a style using jQuery?
Answer:

$(“li”).filter(“.middle”).addClass(“seiected”);
<style>
.selected { color: red; }
</style>

Question 18.
What is JSON?
Answer:
JSON (JavaScript Object Notation) is a simple data exchange format which helps to communicate between JavaScript and server-side technologies like Servlets, JSP (Java Servlet Pages), WCF (Windows Communication Foundation), ASP.NET or Active Server Pages .NET etc.

The format of JSON is as shown below. The below format represents a “Customer” object with “CustomerCode” and “CustomerName” properties as shown in Figure 7.6.

{“CustomerCode”: “1001”, “CustomerName”: “Shiv”}

Now this format can be easily consumed by JavaScript and transformed into JavaScript object. Look at the Figure 7.6 where we have provided JSON to JavaScript variable and you can see how a JavaScript object is evaluated with “CustomerCode” and “CustomerName” properties.

JQUERY Interview Questions in . NET chapter 7 img 4

If you look at the Web architecture it has two parts: browser and server. On the browser side JavaScript is the most

prominent and well established language while on server-side you have different technologies like JSP, ASP.NET, PHP (a recursive backronym; HyperText Preprocessor) etc.

JQUERY Interview Questions in . NET chapter 7 img 5

So if the server-side technologies emit out JSON format which can be easily transformed into a JavaScript object that would really ease the communication between multiple server-side technologies and JavaScript language. Figure 7.7: Web Architecture

Question 19.
How to convert string to JSON object?
Answer:
“JSON.parse” helps us to convert string to JSON object.
var str = ‘{ “Name”: “Shiv”, “Salary”: “1000”}’;
var Customer = JSON.parse(str); alert(Customer.Name);

Question 20.
Was not SOAP meant to do the same thing which JSON does?
Answer:
SOAP is heavy due to XML tags. For example, a SOAP message “<Name>shiv</Name>” will become short, sweet and light in JSON like “Name”: “Shiv”. Second most important it evaluates as JavaScript object. To convert the complicated SOAP XML (extensible Markup Language) as shown in Figure 7.8 in to javascript JSON object would be a tough and tedious task.

JQUERY Interview Questions in . NET chapter 7 img 6

Question 21.
Do all technologies support JSON?
Answer:
Yes, almost all technologies which deal with exchange of data support JSON. For instance if you want to that your WCF service should send JSON message rather than SOAP
you can set the “ResponseFormat ” as “WebMessageFormat. Json” on your operation contract.

[OperationContract]
[Weblnvoke(Method="GET", • UriTemplate="/
GetData",
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json)]
string GetData();

If you want your MVC to emit out JSON data you can return ” JsonResult” as shown below. If you call the below action it will emit out Customer objects in JSON format.

public JsonResult CustomerJson()
{
List<Customer> obj1 = new List<Customer>( );
Thread.Sleep(5000);
Customer obj = new customer ( );
obj.CustomerCode = "1001";
obj1.Add(obj);
return Json(objl, JsonRequestBehavior.AllowGet);
}

If you want to emit JSON using ASP.NET we need to use the “DataContractJsonSerializer” class as shown in the below code. “myPerson” is the class.

DataContractJsonSerializer serializer = new
DataContractJsonSerializer(myPerson.GetType());
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myPerson);
string json = System.Text.Encoding.UTF8.GetString(ms.ToArray( ));
Response.Clear();
Response.ContentType = "application/json;charset=utf-8";
Response.Write(json);
Response.End( );

Question 22.
How can you make a JSON call using jQuery?
Answer:
Let’s assume you have a MVC controller action “getEmployee” which emits out employee JSON object as shown in the below code. Please note you can always emit JSON from any server technology like WCF, ASP.NET, MVC, etc., as discussed in the previous questions.

public JsonResult getEmployee()
{
Emp obj = new Emp();
obj.empcode = "1001";
return Json(obj, JsonRequestBehavior.AllowGet) ;
}

To make a call to the above MVC action using jQuery we need to use "get JSON" method. Below is the simple code for the same. It has three parameters:
1. The first parameter is the URL which emits out JSON. For instance in the below code the URL is
"/Employee/getEmployee".
2. The next parameter helps us to pass data to the resource which emits out JSON currently it’s the MVC action. The second parameter is NULL for now.
3. The last parameter is the callback function which will be invoked once the MVC action returns data. You can see how the “getData" function just displays the "empcode" property. Because the output is in JSON it automatically converts the JSON data to JavaScript object.

$.getJSON("/Employee/getEmployee", null, getData); function getData(data)
{
alert(data.empcode);
}

 

Question 23.
How can we post JSON to Server?
Answer:
We can use the “post” method of jQuery to send data to the server. Below is how the post method call looks like. First parameter is the URL which will accept JSON data, second is the data which we want to send and the final parameter is the callback function where we receive the response.

var mydata ={name: "Shiv", city: "Mumbai"};
$.post("/Send/Request", // URL
mydata, // Data to be sent
function(data, status){alert(data + " " + status);}); // Call back function

Question 24.
How can we post a complete HTML form in JSON format?
Answer:
To post a complete HTML form we need to call “serialize” function as shown in the below code. “form1” is a HTML form. The data given by the function can then be passed to the “post” method of jQuery. “DisplayData” is a callback function to handle the output given by the server.

var Mydata = $(“#form 1 ”). serialize( );
$.post(“/Customer/getCustomer”, JSON. stringify(MyData), DisplayData);

The above posted JSON string is received at the server side “request.inputstream”, below is a simple sample code for the same.

System.10.Stream body = Request.inputstream;
System.10.StreamReader reader = new System.10.StreamReader(body);
string s = reader.ReadToEnd() ;

Question 25.
How can we convert JSON string into C# object?
Answer:
To convert a JSON string to a C# object we need to use the ” JavascriptSerializer” class as shown in the below code.

“JsonString” is the string which has the JSON value and by using “Deserialize” we are converting the string to a C# object. Now this object which we receive is a collection of “key” and “value” pair which can be browsed and accessed in C#.

var jsonser = new JavaScriptSerializer()
var obj = jsonser.Deserialize<dynamic>(JsonString);
foreach (var x in obj)
{
String strvalue = x["value"];
}

Question 26.
What are Single Page Applications (SPA)?
Answer:
SPA means your Web page has the following features:

  • Utilize the browser client power to the maximum by executing the maximum code on the client- side by using JavaScript, HTML and CSS.
  • Rather than loading the complete page necessary HTML fragments or JSON data is loaded as the user demands.
  • JavaScript which handles DOM manipulation, binding, Ajax calls are separated into controllers thus separating views and models.
  • DOM manipulations are replaced by declarative programming.

Algorithms Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on Algorithms

Question 1.
Find if a number is even or odd?
Answer:
A number is even if the remainder yields zero when divided by “2”. A number is odd when the remainder yields zero if divided by “3”. You get the remainder value by using the “%” sign.
Below is a sample code that shows how to check for even and odd numbers in C#.

Console.WriteLine("Enter your number");
int num = Convert.ToIntl6(Console.ReadLine( ));
if (num % 2 == 0) // Is the remainder zero
{
Console.WriteLine("Even number");
}
else
{
Console.WriteLine("Odd number");
}

Question 2.
Write a FizzBuzz program in C#.
Answer:
Ok first let me explain what is FizzBuzz, Fizz.

“Write a C# program that prints numbers from 1 to 100. But for multiples of 3 print “Fizz” instead of the number and for the multiples of 5 print “Buzz”. For numbers which are multiples of both 3 and 5 print “FizzBuzz”.

for (int j = 1; j <= 100; j++)
{
string Output = " ";
if (j % 3 == 0) Output = "Fizz";// Divisible by 3 —> Fizz
if (j % 5 == 0) Output += "Buzz"; // Divisible by 5 —> Buzz
if (Output == "") Output = j.ToString(); // If none then —> number
Console.WriteLine(Output); // Finally print the complete output
}

Question 3.
Can you write a simple C# code to display the Fibonacci series?
Answer:
Let’s first understand what exactly is Fibonacci series is. Fibonacci series is nothing but series of numbers 0, 1, 1,2, 3, 5, and so on.

The specialty of this series is that next number is addition of previous two numbers. Figure 21.1 explains how Fibonacci series works. We first start with 0 and 1. The next number is addition of “0 + 1” which will give us “1”. The next number will be again addition of previous value which is “1” and the current value which is “1 ” which will give us “2” and so on.

Implementing Fibonacci series in C# is a four-step process. Figure 21.2 shows the same in a pictorial format.

Algorithms Interview Questions in . NET chapter 21 img 1

Step 1: Define 3 variables “Prev”, “Next” and “Sum and “Sum=0”.
Step 2: Add “Prev” and “Next” variable to get the Sum. Display the “Sum” variable.
Step 3: Swap “Prev” value to “Next” and “Sum” to “Previous”.
Step 4: Execute “Step 2” and “Step 3” again to get the next Fibonacci value. Below is how the code will look like. Do follow the steps in comment.

//Step 1 Three variables Prev, Next and Sum
// initialized with 1 and -1 values
int Prev = 1;
int Next = -1;
int Sum = 0;
// How many fibonacci numbers you want to print
Console .WriteLine ("How many fibonacci numbers you want to print?'');
int numbers = Convert.ToIntl6(Console.ReadLine());
for (int i = 0; i < numbers; i++)
{
// Step 2: Add the previous and next numbers
Sum = Prev + Next;
Console.WriteLine(Sum);
// Step 3: Swap Prev to next and Sum to Prev
Next = Prev;
Prev = Sum;
// Step 4: Run Step 2 and Step 3 again
}

Question 4.
Can you write a logic for bubble sort in C#?
Answer:
Bubble sort is a sorting algorithm which steps through a collection repeatedly, comparing and,swapping until the collection gets sorted. Figure 21.3 a simple pictorial representation of how bubble sort works. We have a simple number collection of values 5, 1, 3 and 4 and we would like to sort them in an ascending manner.

Step 1: So we first start with number 5. The adjacent number to 5 is 1. So we compare 5 with 1. Now 5 is greater than 1 so we swap position of 1 with 5 and 5 with 1. Look at Step 2 for the final image after swapping.

Step 2: Now we compare 5 with 3. 5 is greater than 3 so we swap position of 5 with 3 and 3 with 5. This continues until 5 has been compared with all numbers in the list. Step 4 is the final position for number 5. .
Now we take the second number, i.e., 1 and we compare and swap 1 with all other numbers until it reaches its final position. This is done with all numbers in the collection.

Algorithms Interview Questions in . NET chapter 21 img 2

Below is thecode for bubble sort in C#.

static public List<int> bubblesort(List<int> unsorted)
{
int temp;
for (int i = 1; i <= unsorted.Count; i++)
for (int j = 0; j < unsorted.Count - i; j++)
if (unsorted[j] > unsorted[j + 1])
{
temp = unsorted[j];
unsorted[j] = unsorted[j + 1];
unsorted[j +1] = temp;
}
return unsorted;
}

Question 5.
What is inserted sort algorithm?
Answer:
In inserted sorted algorithm we compare the current element value with the previous element value. If the current value is smaller than the previous value we swap. This continues until the complete list is sorted.
Let us try to understand the same by using the below diagram, in the Figure 21.4 you can see we have an unsorted list with values 6,1, 3, 2.

Algorithms Interview Questions in . NET chapter 21 img 3

Step 1: So we start with the first element i.e. “6”.There is no element before 6, so we leave it and we start from 1. We compare “6” and “1”. “1” is smaller than “6”, so we swap.

Step 2: Now we move to the next element “3”. Is “3” smaller than “6”, yes. So we again swap.

Step 3: Now we compare “6” with the next element “2”. “2” is smaller so we swap again. There are no more further elements which can be compared with “6”. So the “6” value iteration stops here.

Step 4: Now we take the next element “1”. There is no element before “1” so we move ahead. We move to the next element “3”. Is “3” smaller than “1”, no, so things are left where they are. So the iteration for “1” is done.We then move to the next element “3”. We compare “3” with “2”. “2” is smaller than “3” so we swap. Now “3” is compared with the next element “6”. “3” is smaller than “6” so the elements .are left where they are.

Step 5: Now we take the last element “2”. “2” element is larger is than “1”, so “2” and “1” stay where they are. The complete collection is now sorted.
Below is a simple C# inserted algorithm code.

ClassProgram
{
// array of integers which holds unsorted value.
Privatestaticint[ ] UnSortedArray = newint[4]{6, 1, 3, 2};
// Insertion Sort Algorithm
Staticvoid Main(string[ ] args)
{
sortArray( );
foreach (int i in UnSortedArray)
{
Console.WriteLine(i);
}
Console.ReadLine( ) ;
}
publicstaticvoid sortArray( )
{
int MainLoop; // This variable will helps us loop through all the elements
int InnerLoop; // This variable will help us loop through all elements for every value int CurrentValue;
for (MainLoop = 1; MainLoop < UnSortedArray.Count(); MainLoop++) // loop through all the elements in the array.
{
CurrentValue = UnSortedArray[MainLoop]; // Take the current value
InnerLoop = MainLoop;
// Loop through all elements for that value . while ((InnerLoop > 0) && (UnSortedArray[InnerLoop - 1]
> CurrentValue))
{
//if the previous value is greater than currentvalue swap UnSortedArray[InnerLoop] = UnSortedArray[InnerLoop - 1] ; InnerLoop = InnerLoop - 1;
}
// If previous value is not greater then just keep the value where they are.
UnSortedArray[InnerLoop] = Currentvalue; ’
}
}

Question 6.
How does selection sort algorithm work?
Answer:
Selection sort is the most simples sorting algorithm. It finds the lowest value from the collection and moves it to the left. This is repeated until the complete collection is sorted.
Figure 21.5 shows a pictorial representation of how selection sort works. We have simple collection down below which has 5, 7,1, and 0 values.

Step 1: Find the smallest value from the collection. In the current collection the smallest value is “0”. Move this smallest value to the left hand side.

Step 2: Iterate again to find the next smallest value.

Algorithms Interview Questions in . NET chapter 21 img 4

The next smallest value is “1”. Move this value to the left hand side before the first smallest value.
In this manner continue with all elements in a collection and your list is sorted.
Below is a simple C# code for selection algorithm.

// array of integers to hold values privatestaticint[] a = newint[4]{2, 8,0, 3};
staticvoid Main(string[] args)
{
Sort();
foreach (int temp in a)
{
Console.WriteLine(temp);
}
Console.ReadLine( );
}
publicstaticvoid Sort( )
{
int i, j ;
int min, temp;
for (i = 0; i < a.Count( ) - 1; i++) // Loop through each element
{
min = i; // Assume that he is the smallest
for (j = i + 1; j < a.Count(); j++) // Loop through the remaining element
{
if (a[j] < a[min]) // If the current value smaller than the min
{
min = j; // Swap the values
}
}
temp = a[i]; // Store the current value in temp variuable
a[i] = a[min]; // Swap the minimum value to the current position
a[min] = temp; // Swap the current value to the minimum value
position
}
}

 

ASP.NET MVC (Model View Controller) Interview Questions in .NET

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

.NET Interview Questions on ASP.NET MVC (Model View Controller)

Note: In case you are new to MVC and you want to kick start learning MVC we would recommend you to go 
through 5 videos provided in the “Learn MVC Step by Step” section.
Lab 1: Simple Hello world.
Lab 2: Explain MVC Routing.
Lab 3: Explain ViewData, ViewBag, TempData & Session.
Lab 4: Explain Model and Strongly typed views.
Lab 5: Explain Model Binders.

Question 1.
What is MVC?
Answer:
MVC is an architectural pattern that separates the representation and the user interaction. It’s divided into three broader sections, “Model”, “View”, and “Controller”. Figure 6.1 shows are how each one of them handles the task.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 1

  • The “View” is responsible for the look and feel.
  • “Model” represents the real-world object and provides data to the “View”.
  • The “Controller” is responsible to take the end-user request, and load the appropriate “Model” and “View”.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 2

Question 2.
Explain the MVC application life cycle.
Answer:

Note: There is nothing as such called an MVC life cycle. I think a lot of people are obsessed with the ASP.NET
 page life cycle and they think there is a life cycle in MVC as well. To be specific the MVC request goes through 
various steps of execution and that's what is termed as the MVC application life cycle.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 3

Any Web application has two main execution steps first understanding the Request and depending on the type of the request sending out appropriate Response as shown in Figure 6.2. MVC application life cycle is not different it has two main phases first creating the request object and second sending our response to the browser.

Creating the request object: The request object creation has four major steps. Below is a detailed explanation of the same.

Step 1 – Fill route: MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the routing table with routes collection. This filling of the routing table happens in the global.asax file.

Step 2 – Fetch route: Depending on the URL sent “UrlRoutingModule” searches the routing table to create a “RouteData” object which has the details of which controller and action to invoke.

Step 3 – Request context created: The “RouteData” object is used to create the “RequestContext” object.

Step – 4 Controller instance created: This request object is sent to the “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.
Creating Response object: This phase has two steps executing the action and finally sending the response as a result to the view.

Step 5 – Execute Action: The “ControllerActionlnvoker” determines which action to be executed and executes the action.

Step 6 – Result sent: The action method executes and creates the type of result which can be a view result, file result, JSON (JavaScript Object Notation) result, etc.

So in all, there are six broad steps that get executed in the MVC application life cycle.

Note: In case you are not able to remember the above steps during iriterview remember the acronym 
FFRCER(Fight For Respect Can Evoke Revolution).

Question 3.
Is MVC suitable for both Windows and Web applications?
Answer:
MVC architecture is suited for Web applications than windows. For window application MVP, i.e., “Model View Presenter” is more applicable. If you are using WPF and Silverlight, MWM is more suitable due to bindings.

Question 4.
What are the benefits of using MVC?
Answer:
There are two big benefits of MVC:

  • Separation of concerns is achieved as we are moving the code behind to a separate class file. By moving the binding code to a separate class file we can reuse the code to a great extent.
  • Automated Ul testing is possible because now the behind code (Ul interaction code) has moved to a simple.NET class. This gives us the opportunity to write unit tests and automate manual testing.

Question 5.
Is MVC different from a 3-layered architecture?
Answer:
MVC is an evolution of a 3-layered traditional architecture as shown in Figure 6.3. Many components of the 3-layered architecture are part of MVC. So Table below shows how the mapping goes.

Functionality 3-layered / tiered architecture Model view controller architecture
Look and Feel User interface View
Ul logic User interface Controller
Business logic /validations Middle layer Model
The request is first sent to User interface Controller
Accessing data Data access layer Data access layer

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 4

Question 5.
What is the latest version of MVC?
Answer:
MVC 6 is the latest version which is also termed as ASP vNext.

Question 6.
What is the difference between each version of MVC 2, 3,4, 5, and 6?
Answer:
MVC 6
ASP.NET MVC and Web API have been merged into one.
Dependency injection is inbuilt and part of MVC.
Side-by-side, deploy the runtime and framework with your application.
Everything is packaged with NuGet, including the .NET runtime itself.
New JSON-based project structure.
No need to recompile for every change. Just hit save and refresh the browser.
The compilation is done with the new Roslyn real-time compiler.
vNext is open-source via the .NET Foundation and is taking public contributions.
vNext (and Roslyn) also run on Mono, on both Mac and Linux today.

MVC 5
OneASP.NET.
Attribute-based routing.
Asp.Net identity.
Bootstrap in the MVC template.
Authentication filters.
Filter overrides.

MVC 4
ASP.NET Web API (Application Programming Interface)
Refreshed and modernized default project templates.
New mobile project template.
Many new features to support mobile apps.
Enhanced support for asynchronous methods.

MVC 3
Razor
Readymade project templates.
HTML 5 enabled templates.
Support for multiple view Engines.
JavaScript and Ajax.
Model validation improvements.

MVC 2
Client-side validation.
Templated helpers.
Areas.
Asynchronous controllers.
Html. ValidationSummary helper method.
DefaultValueAttribute in action-method parameters.
Binding binary data with model binders.
DataAnnotations attributes.
Model-validator providers.
New RequireHTTPsAttribute action filter.
Templated helpers.
Display model-level errors

Question 7.
What are HTML helpers in MVC?
Answer:
HTML helpers help you to render HTML controls in the view. For instance, if you want to display an HTML textbox on the view, below is the HTML helper code.

<%= Html. TextBox(“LastName’) %>

For the checkbox below is the HTML helper code. In this way, we have HTML helper methods for every HTML control that exists.

<%= Html.CheckBox(“Married”) %>

Question 8.
What is the difference between “HTML.TextBox” vs “HTML.TextBoxFor”?
Answer:
Both provide the same HTML output, “Html .TextBoxFor” is strongly typed while “Html .TextBox” isn’t.
Below is a simple HTML code that just creates a simple textbox with “CustomerCode” as a name.

Html. TextBox(“CustomerCode”)

Below is “Html. TextBoxFor” code which creates HTML textbox using the property name ‘CustomerCode” from object “m”.

Html.TextBoxFor(m => m.CustomerCode)

In the same way, we have for other HTML controls like for checkbox, we have
“Html.checkBox” and
“Html.CheckBoxFor”.

Question 9.
Explain the importance of MVC model binders.
Answer:
Model binder maps HTML form elements to the model as shown in Figure 6.4. It acts as a bridge between HTML Ul and MVC model.
Take the below simple HTML form example:

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 5

<formid="frml" method=post action="/Customer/SubmitCustomer">
             Customer code: <inputname="CCode"type="text"/>
             Customer name: <inputname="CName''type="text"/>
            <input type=submit/>
</form>

Now this form needs to fill the below “Customer” class model. If you see the HTML control name they are different from the class property name. For example HTML textbox control name is “CCode” and the class property name is “CustomerCode”. This mapping code is written in HTML binder classes.

publicclassCustomer
{
     publicstring CustomerCode { get; set; }
     publicstring CustomerName { get; set; }
}

To create a model binder we need to implement “iModelBinder” interface and mapping code needs to be written in the “BindModel” method as shown in the below code.

publicclassCustomerBinder: IModelBinder
{
       publicobject BindModel(ControllerContext controllerContext,
       ModelBindingContext bindingContext)
       {
            HTTPRequestBase request = controllerContext.HTTPContext.Request;
            string strCustomerCode = request.Form.Get("CCode");
            string strCustomerName = request.Form.Get("CName");

            returnnewCustomer
            {
                 CustomerCode = strCustomerCode,
                 CustomerName = strCustomerName
           } ;
      }
}

Now in the action result method, we need to use the “ModelBinder” attribute which will attach the binder with the class model.

publicActionResult SubmitCustomer([ModelBinder(typeof(CustomerBinder))] Customer obj) 
{
        return View("DisplayCustomer");
}

Question 10.
What are routing in MVC?
Answer:
Routing helps you to define user friendly URL (Uniform Resource Locator) structure and map those URL structure to the controller.
For instance let’s say we want that when any user types “HTTP: //localhost/View/ViewCustomer/”, it goes to the “Customer”. Controller and invokes “DisplayCustomer” action. This is defined by adding an entry in to the “routes” collection using the “MapRoute” function. Below is the underlined code which shows how the URL structure and mapping with controller and action is defined.

routes.MapRoute(
"View", // Route name
"View/ViewCustomer/{id}", // URL with parameters
new { controller = "Customer", action = "Display-Customer", id
= UrlParameter.Optional }); // Parameter defaults

Question 11.
Where is the route mapping code written?
Answer:
The route mapping code is written in “RouteConfig.es” file and registered using “global.asax” application start event.

Question 12.
Can we map multiple URL’s to the same action?
Answer:
Yes, you can, you just need to make two entries with different key names and specify the same controller and action.

Question 13.
Explain attribute-based routing in MVC.
Answer:
This is a feature introduced in MVC 5. By using the “Route” attribute we can define the URL structure. For example, in the below code we have decorated the “GotoAbout” action with the route attribute. The route attribute says that the “GotoAbout” can be invoked using the URL structure “Users/ about”.

public class HomeController: Controller
{
       [Route("Users/about")]
       public ActionResult GotoAbout()
       {
            return View( );
       }
}

Question 14.
What is the advantage of defining route structures in the code?
Answer:
Most of the time developers code in the action methods. Developers can see the URL structure right upfront rather than going to the “routeconfig.es” and see the lengthy codes. For instance in the below code the developer can see right upfront that the “GotoAbout” action can be invoked by four different URL structure. .

This is much user friendly as compared to scrolling through the “routeconfig.es” file and going through the length line of code to figure out which URL structure is mapped to which action.

public class HomeController: Controller
{
       [Route("Users/about")]
       [Route("Users/WhoareWe")]
       [Route("Users/OurTeam")]
       [Rout("Users/aboutCompany")]
       public ActionResult GotoAbout()
       {
            return View( );
       }
}

Question 15.
How can we navigate from one view to other view using hyperlink?
Answer:
By using “ActionLink” method as shown in the below code. The below code will create a simple URL which help to navigate to the “Home” controller and invoke the “GotoHome” action.

<%= Html.ActionLink(“Home”, “Gotohome”) %>

Question 16.
How can we restrict MVC actions to be invoked only by GET or POST?
Answer:
We can decorate the MVC action by “HTTPGet” or “HTTPPost” attribute to restrict the type of HTTP calls. For instance you can see in the below code snippet the “DisplayCustomer” action can only be invoked by “HTTPGet”. If we try to make HTTP post on “DisplayCustomer” it will throw an error.

[HTTPGet]
public ViewResult DisplayCustomer(int id)
{
       Customer objCustomer = Customers[id];
       return View("DisplayCustomer", objCustomer);
}

Question 17.
How can we maintain session in MVC?
Answer:
Sessions can be maintained in MVC by three ways tempdata, viewdata and viewbag as shown in Figure 6.5.

Question 18.
What is the difference between tempdata, viewdata and viewbag?
Answer:

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 6

Tempdata: Tempdata maintains data until its read. So once you set tempdata until it is not read the data is maintained in every request.

Note: In the next question we have talked about “peek” and “keep” which interviewer can ask to make you 
confuse more on “TempData”do read more about the same.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 7

View Data: Helps to maintain data when you move from controller to view.

View Bag: It is a dynamic wrapper around view data. When you use “View Bag” typecasting is not required. It uses the dynamic keyword internally as shown in Figure 6.6.

Session variables: Session variables maintain data for a complete session that means right from the browser session started till the browser is closed.

Hidden fields and HTML controls: Helps to maintain data from Ul (User Interface) to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Question 19.
What is life of “TempData”?
Answer:
“TempData” is available for the current request and in the subsequent request it’s available depending on whether “TempData” is read or not. So if “TempData” is once read it will not be available in the subsequent request.

Question 20.
What is the use of Keep and Peek in “TempData”?
Answer:
Once “TempData” is read in the current request it’s not available in the subsequent request. If we want “TempData” to be read and also available in the subsequent request then after reading we need to call “Keep” method as shown in the code below.

@ TempData[“MyData 
TempData.Keep(“MyData’);

The more shortcut way of achieving the same is by using “Peek”. This function helps to read as well advices MVC to maintain “TempData” for the subsequent request.

string str = TempData. Peek(“Td”). ToString( );

Question 21.
What are partial views in MVC?
Answer:
Partial view is a reusable view (like a user control) which can be embedded inside other view. For example, let’s say all your pages of your site have a standard structure with Left Menu, Header and Footer as shown in the Figure 6.7.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 8

For every page you would like to reuse the Left Menu, Header and Footer controls. So you can go and create partial views for each of these items and then you call that partial view in the main view.

Question 22.
How did you create partial view and consume the same?
Answer:
When you add a view to your project you need to check the “Create a partial view (.ascx)’’ check box.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 9

Once the partial view is created you can then call the partial view in the main view using “Html .RenderPartial” method as shown in the below code snippet.

<body>
<div>
<% Html.RenderPartial("MyView"); %>
</div>
</body>

Question 23.
How can we do validations in MVC?
Answer:
One of the easy ways of doing validation in MVC is by using data annotations. Data annotations are nothing but attributes which you can be applied on the model properties. For example in the below code snippet we have a simple “Customer” class with a property “CustomerCode”.
This “CustomerCode” property is tagged with a “Required” data annotation attribute. In other words if this model is not provided customer code it will not accept the same.

public class Customer
{
       [Required(ErrorMessage="Customer code is required")]
       public string CustomerCode
       {
            set;
            get;
       }
}

In order to display the validation error message we need to use “ValidateMessageFor” method which belongs to the “Html” helper class.

<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />
<%}%>

Later in the controller we can check if the model is proper or not by using “ModelState. isValid” property and accordingly we can take actions.

public ActionResult PostCustomer(Customer obj)
{
      if (ModelState.IsValid)
      {
           obj.Save();
           return View("Thanks");
      }
      else
      {
          return View("Customer");
      }
}

Figure 6.9 is a simple view of how the error message is displayed on the view.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 10

Question 24.
Can we display all errors in one go?
Answer:
Yes we can, use “ValidationSummary” method from HTML helper class.

<%= Html. ValidationSummary( ) %>

Question 25.
What are the other data annotation attributes for validation in MVC?
Answer:
If you want to check string length, you can use “StringLength”.

[StringLength( 160)]
public string FirstName { get; set;}

In case you want to use regular expression, you can use “RegularExpression” attribute.

[RegularExpression(@”[A-Za-zO-9._%+-]+@[A-Za-zO-9.-]+\.[A-Za-z]{2, 4}”)] 
public string Email { get; set;}

If you want to check whether the numbers are in range, you can use the “Range” attribute.

[Range(10, 25)] 
public int Age { get; set;}

Some time you would like to compare value of one field with other field, we can use the “Compare” attribute.

public string Password { get; set; }
[Compare(“Password”)]
public string ConfirmPass { get; set; }

In case you want to get a particular error message, you can use the “Errors” collection.

var ErrMessage = ModelState[“Emaii”].Errors[0].ErrorMessage;

If you have created the model object yourself you can explicitly call “TryUpdateModel” in your controller to check if the object is valid or not.

TryUpdateModel(NewCustomer);

In case you want add errors in the controller you can use “AddModelError” function.

ModelState.AddModelError(“FirstName”, “This is my server-side error.”);

Question 26.
How can we enable data annotation validation on client-side?
Answer:
It’s a two-step process. In first step, give reference the necessary j query files.

<script src="<%= Url.Content("-/Scripts/jQuery-1.5.1.js") %>" type="text/ j avascript"x/script>
<script src="<%= Url.Content("-/Scripts/jQuery.validate.js") %>" type="text/ javascript"x/script>
<script src="<%= Url.Content("-/Scripts/jQuery.validate.unobtrusive.j s") %>" type = "text/javascript"x/script>

Second step is to call “EnableClientValidation” method.

<% Html.EnableClientValidationO; %>

Question 27.
Explain Areas in MVC.
Answer:
Areas help you to group functionalities into independent modules thus making your project more organized. For example, in the Figure 6.10 MVC project is shown where we have four controller classes and as time passes by if more controller classes are added it will be difficult to manage. In bigger projects you will end up with 100’s of controller classes making life hell for maintenance.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 11

If we group controller classes into logical section like “Invoicing” and “Accounting” that would make life easier and that’s what “Areas” are meant to as shown in Figure 6.13.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 12

You can add an area by right clicking on the MVC solution and clicking on “Area…” menu as shown in the Figure 6.12.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 13

In the Figure 6.13, we have two “Areas” created “Accounts” and “Invoicing” and in that I have put the respective controllers. You can see how the project is looking more organized as compared to the previous state.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 14

Question 28.
What is Razor in MVC?
Answer:
It’s a lightweight view engine. Till MVC we had only one view type, i.e., ASPX, Razor was introduced in MVC 3.

Question 29.
Why Razor when we already had ASPX?
Answer:
Razor is clean, lightweight and syntaxes are easy as compared to ASPX. For example in ASPX to display simple time we need to write.

<%=Date Time. Now%>

In Razor it’s just one line of code.

@DateTime.Now

Question 30.
So which is a better fit Razor or ASPX?
Answer:
Microsoft Razor is more preferred because it’s lightweight and has simple syntaxes.

Question 31.
Explain the difference between layout and master pages.
Answer:
Layout are like master pages in ASP.NET Web form. Master pages give a standard look and feel for Web form views while layout gives standard look and feel or acts like a template for Razor views.

Question 32.
How to apply layout to Razor views?
ANswer:
So first we need to create a template file as shown in the below code.

<div>
@RenderSection("Header")
@RenderBody( )
@RenderSection("Footer")
</div>

And then apply this template to the view as shown below and display data in those respective sections.

@{Layout = "~/Views/Defaultl/_LayoutPagel.cshtml";}
This is body
@section Footer{Copyright 2015-2016}
@section Header{Welcome to my site}

Question 33.
Explain the concept of Scaffolding.
Answer:

Note: Do not get scared with the word. Its actually a very simple thing.

Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. CRUD stands for Create, Read, Update and Delete.
So to generate code using scaffolding technique we need to select one of the types of templates (leave the empty one) as shown in Figure 6.14.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 15

For instance if you choose “using Entity Framework” template as shown in Figure 6.15 the following code is generated.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 16

It creates controller code, view and also table structure as shown in the Figure 6.16.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 17

Question 34.
What does scaffolding use internally to connect to database?
ANswer:
It uses Entity Framework internally.

Question 35.
How can you do authentication and authorization in MVC?
Answer:
You can use windows or forms authentication for MVC.

Question 36.
How to implement Windows authentication for MVC?
Answer:
For windows authentication you need to go and modify the “Web.config” file and set authentication mode to Windows.

<authentication mode="Windows"/>
<authorization>
<deny users = "?''/>
</authorization>

Then in the controller or on the action you can use the “Authorize” attribute which specifies the users who can access these controllers and actions. Below is the code snippet for the same. Now only the users specified in the controller and action can access the same.

[Authorize(Users= @"WIN-3LI600MWLQN\Administrator"),
public class StartController: Controller
{
       //
      // GET: /Start/
      [Authorize(Users = @"WIN-3LI600MWLQN\Administrator")]
      public ActionResult Index()
      {
              return View("MyView");
      }
}

Question 37.
How do you implement forms authentication in MVC?
Answer:
Forms authentication is implemented the same way as we do in ASP.NET. So the first step is to set authentication mode equal to forms. The “loginUrl” points to a controller here rather than page.

<authentication mode="Forms">
<forms loginUrl="~/Home/Login" timeout="2880"/>
</authentication>

We also need to create a controller where we will check the user is (authorized) proper or not. If the user is proper (authorized) we will set the cookie value.

public ActionResult Login( )
{
       if ((Request.Form["txtUserName"] == "Shiv") &&
       (Request.Form["txtPassword"] == "Shiv@123"))
       {
              FormsAuthentication.SetAuthCookie("Shiv", true);
              return View("About");
      }
      else
      {
             return View("Index");
      }
}

All the other actions need to be attributed with “Authorize” attribute so that any unauthorized user if he makes a call to these controllers it will redirect to the controller ( in this case the controller is “Login”) which will do authentication.

[Authorize]
PublicActionResult Default ( )
{
      return View( );
}
[Authorize]
PublicActionResult About( )
{
     return View();
}

Question 38.
How to implement Ajax in MVC?
Answer:
You can implement Ajax in two ways in MVC:

  • Ajax libraries
  • jQuery (a cross-platform JavaScript)

Below is a simple sample of how to implement Ajax by using “Ajax” helper library, in the below code you can see we have a simple form which is created by using “Ajax.BeginForm” syntax. This form calls a controller action called as “getcustomer”. So now the Submit action click will be an asynchronous Ajax call.

<script language="javascript">
function OnSuccess(data1)
{
       // Do something here
}
</script>
<div>
<%
        var AjaxOpt = new AjaxOptions{OnSuccess="OnSuccess"};
%>
<% using (Ajax.BeginForm("getCustomer", "MyAjax", AjaxOpt}) { %>
<input id="txtCustomerCode" type="text" /xbr />
<input id="txtCustomerName" type="text" /xbr />
<input. id="Submit2" type="submit" value= "submit"/></div>
<%} %>

In case you want to make Ajax calls on hyperlink clicks <X you can use “Ajax. ActionLink” function as shown Aj
in the Figure 6.17.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 18

So if you want to create Ajax asynchronous hyperlink by name “GetDate” which calls the “GetDate” function v» on the controller, below is the code for the same. Once the controller responds this data is displayed in the HTML
DIV tag by name “DateDiv”.

<span id=”DateDiv” />
<%:
Ajax.ActionLink(“Get Date”, “GetDate”,
new AjaxOptions (UpdateTargetld = “DateDiv” })
%>

Below is the controller code. You can see how “GetDate” function has a pause of 10 seconds.

public class DefaultlController: Controller
{
      public string GetDate( )
      {
          Thread.Sleep(10000);
          return DateTime2Now.ToString( );
      }
}

The second way of making Ajax call in MVC is by using jQuery. In the below code you can see we are making an Ajax POST call to a URL “/MyAjax/getCustomer”. This is done by using “$ .post”. All this logic is put in to a function called as “GetData” and you can make a call to the “GetData” function on a button or a hyperlink click event as you want.

function GetData( )
{
      var url = "/MyAjax/getCustomer";
      $.post(url, function (data)
     {
                $("#txtCustomerCode").val(data.CustomerCode) ;
                $("#txtCustomerName").val(data.CustomerName);
     }
}

Question 39.
What kind of events can be tracked in Ajax?
Answer:

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 19

Question 39.
What is the difference between “ActionResult” and “ViewResult”?
Answer:
“ActionResult” is an abstract class while “ViewResult” derives from “ActionResult” class. “ActionResult” has several derived classes like “ViewResult”, ” JsonResult”, “FileStreamResult” and so on.

“ActionResult” can be used to exploit polymorphism and dynamism. So if you are returning different types of view dynamically “ActionResult” is the best thing. For example in the below code snippet you can see we have a simple action called as “Dynamicview”. Depending on the flag
(“IsHtmlView”) it will either return “ViewResult” or “JsonResult”.

public ActionResult DynamicView(bool IsHtmlView)
{
      if (IsHtmlView)
      return View(); // returns simple ViewResult
      else
      return Json( ); // returns JsonResult view
}

Question 40.
What are the different types of results in MVC?
Answer:

Note: It’s difficult to remember all the twelve types. But some important ones you can remember 
for the interview are “ActionResult”, “ViewResult” and “JsonResult”. Below is a detailed list for your interest.

There twelve kinds of results in MVC, at the top is “ActionResult”class which is a base class that can have eleven subtypess as listed below.

  1. ViewResult – Renders a specified view to the response stream.
  2. PartialviewResult – Renders a specified partial view to the response stream.
  3. EmptyResult – An empty response is returned.
  4. RedirectResult – Performs an HTTP (HyperText Transfer Protocol) redirection to a specified URL.
  5. RedirectToRouteResult – Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data.
  6. JsonResult – Serializes a given object to JSON format.
  7. javaScriptResult – Returns a piece of JavaScript code that can be executed on the client.
  8. Content Re suit – Writes content to the response stream without requiring a view.
  9. FileContentResuit – Returns a file to the client.
  10. FileStreamResult – Returns a file to the client, which is provided by a Stream.
  11. FilePathResult – Returns a file to the client.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 20

Question 41.
What are “ActionFilters”in MVC?
Answer:
“ActionFilters” helps you to perform logic while MVC action is executing or after a MVC action has executed as shown in Figure 6.19.
Action filters are useful in the following scenarios:

  1. Implement post-processing logic before the action happens.
  2. Cancel a current execution.
  3. Inspect the returned value.
  4. Provide extra data to the action.

You can create action filters by two ways:

  • Inline action filter.
  • Creating an “ActionFilter” attribute.

To create a inline action attribute we need to implement “iActionFilter” interface. The “IActionFilter” interface has two methods “OnActionExecuted” and “OnActionExecuting”. We can implement pre-processing logic or cancellation logic in these methods.

public class DefaultlController: Controller, IActionFilter
{
         public ActionResult Index(Customer obj)
        {
                 return View(obj);
        }
        void IActionFilter.OnActionExecuted(ActionExecutedContext filterContext)
        {
            Trace.WriteLine("Action Executed");
        }
       void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {
           Trace.WriteLine("Action is executing");
       }
}

The problem with inline action attribute is that it cannot be reused across controllers. So we can convert the inline action filter to an action filter attribute. To create an action filter attribute we need to inherit from “ActionFilterAttribute” and implement “IActionFilter” interface as shown in the below code.

public class MyActionAttribute: ActionFilterAttribute, IActionFilter
{
        void IActionFilter.OnActionExecuted(ActionExecutedContext
        filterContext)
        {
                 Trace .WriteLine ( "Action Executed");
        }
       void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
       {
                 Trace.WriteLipe("Action executing");
      }
}

Later we can decorate the controllers on which we want the action attribute to execute. You can see in the below code I have decorated the “DefaultlController” with “MyActionAttribute” class which was created in the previous code.

[MyActionAttribute]
public class DefaultlController: Controller
{
      public ActionResult Index(Customer obj)
      {
             return View(obj);
      }
}

Question 42.
What are the different types of action filters?
Answer:

  1. Authorization filters
  2. Action filters
  3. Result filters
  4. Exception filters

Question 43.
If we have multiple filters, what’s the sequence for execution?
Answer:

  1. Authorization filters
  2. Action filters
  3. Response filters
  4. Exception filters

Question 44.
Can we create our custom view engine using MVC?
Answer:
Yes, we can create our own custom view engine in MVC. To create our own custom view engine we need to following 3 steps:
Let’ say we want to create a custom view engine where in the user can type a command like “<DateTime>” and it should display the current date and time.

Step 1: We need to create a class which implements “iview” interface. In this class we should write the logic of how the view will be rendered in the “Render” function. Below is a simple code snippet for the same.

public class MyCustomView: IView
{
       private string _FolderPath; // Define where our views are stored
       public string FolderPath
       {
             get { return _FolderPath; }
             set { _FolderPath = value; }
       }
       public void Render(ViewContext viewContext, System.10.TextWriter writer) ‘
       {
            // Parsing logic <dateTime>
           // read the view file
          string strFileData = File.ReadAllText(_FolderPath);
         //we need to and replace <datetime> datetime.now value
        string strFinal = strFileData.Replace("<DateTime>",
        DateTime.Now.ToString());
       // this replaced data has to sent for display
       writer.Write(strFinal);
     }
}

Step 2: We need to create a class which inherits from “VirtualPathProviderViewEngine” and in this class we need to provide the FolderPath and the extension of the view name. For instance for Razor the extension is “cshtml”, for aspx the view extension is “.aspx”, so in the same way for our Customview we need to provide an extension. Below is how the code looks like. You can see the “ViewLocationFormats” is set to the “Views” folder and the extension is ” .myview”.

public class MyViewEngineProvider: VirtualPathProviderViewEngine
{
      //We will create the object of Mycustom view
      public MyViewEngineProvider() // constructor
      {
             // Define the location of the View file
             this.ViewLocationFormats = new string[ ] { "-/Views/{1}/
             {0}.myview", "-/Views/Shared/{0}.myview" }; //location and 
             extension of our views
      }
      protected override IView CreateView(ControllerContext
      controllerContext, string viewPath, string masterPath)
      {
             var physicalpath =
             controllerContext.HTTPContext.Server.MapPath(viewPath);
             MyCustomView obj = new MyCustomView(); // Custom view engine
             class
             obj.FolderPath = physicalpath; // set the path where the views 
             will be stored
             return obj; // returned this view parsing logic so that it can 
             be registered in the view engine collection
     }
protected override IView CreatePartialView(ControllerContext 
controllerContext, string partialPath)
{
            var physicalpath =
            controllerContext.HTTPContext.Server.MapPath(partialPath);
            MyCustomView obj = new MyCustomView(); // Custom view engine
            class
            obj.FolderPath = physicalpath; // set the path where the views 
            will be stored
            return obj; // returned this view parsing logic so that it can 
            be registered in the view engine collection
     }
}

Step 3: We need to register the view in the custom view collection. The best place to register the custom view engine in the “ViewEngines” collection is the “global.asax” file. Below is the code snippet for the same.

protected void Application_Start( )
{
     // Step3: register this object in the view engine collection
     ViewEngines.Engines.Add(new MyViewEngineProvider());
     ......
}

Below is a simple output format of the CustomView written using the commands defined at the top as shown in Figure 6.20.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 21

If you invoke this view you should see the following output as shown in Figure 6.21.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 22

Question 45.
How to emit JSON from MVC?
Answer:
In MVC we have “JsonResult” class by which we can return back data in JSON format. Below is a sample code which returns back “Customer” object in JSON format using “JsonResult”.

public JsonResult getCustomer()
{
      Customer obj = new Customer();
      obj .CustomerCode = "1001";
      obj.CustomerName = "Shiv";
      return Json(obj, JsonRequestBehavior.AllowGet);
}

Figure 6.22 shows the JSON (JavaScript Object Notation) output of the above code if you invoke the action via the browser.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 23

Question 46.
What is “WebAPI”?
Answer:
HTTP is the most used protocol. For past many years browser was the most preferred client by which we can consume data exposed over HTTP. But as years passed by client variety started spreading out. We had demand to consume data on HTTP from clients like mobile, JavaScripts, Windows application, etc.

For satisfying the broad range of client ReSTor “REST” (Representational State Transfer) was the proposed approach. You can read more about “REST” from WCF chapter.
“WebAPI” is the technology by which you can expose data over HTTP following REST principles.

Question 47.
How does WCF differ from WEB API?
Answer:

WCF WEB API
Multi-protocol hosting Heavy weight because of complicated WSDL (Web Services Description Language) structure. Lightweight, only the necessary information is transferred.
Protocol Independent of protocols. Only for HTTP protocol.
Formats To parse SOAP (Simple Object Access Protocol) message, the client needs to understand WSDL format. Writing custom code for parsing WSDL is a heavy duty task. If your client is smart enough to create proxy objects like how we have in .NET (add reference) then SOAP is easier to consume and call. Output of “WebAPI” are simple string message, JSON, Simple XML format etc. So writing parsing logic for the same in very easy.
Principles SOAP follows WS-* specification. WebAPI follows REST principles. (Please refer about REST in WCF chapter).

Question 48.
With WCF also you can implement REST, so why “WebAPI”?
Answer:
WCF was brought in to implement SOA, never the intention was to implement REST.”WebAPH is built from scratch and the only goal is to create HTTP services using REST. Due to the one point focus for creating “REST” service “WebAPI” is more preferred.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 24

Question 49.
How to implement “WebAPI” in MVC?
Answer:
Below are the steps to implement “WebAPI”:

Step1: Create the project using the “WebAPI” template as shown in Figure 6.23.
Step 2: Once you have created the project you will notice that the controller now inherits from “ApiController” and you can now implement “POST”, “GETt”, “PUT” and “DELETE” methods of HTTP protocol.

public class ValuesController: ApiController
{
       // GET api/values
       public IEnumerable<string> Get( )
       {
            return new string [ ] { "value1" , "value2" } ;
       }
       // GET api/values/5
       public string Get(int id)
       {
             return "value";
       }
       //POST api/values
       public void post { [ Frombody ] string value ]
       {
       }
       // PUT api/values/5
       public void Put(int id, [FromBody ] string value ]
       {
       }
      // DELETE api/values/5
       public void Delete(int id)
       {
       }
}

Step 3: If you make a HTTP GET call you should get the results as shown in Figure 6.24.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 25

Question 50.
How can we detect that a MVC controller is called by POST or GET?
Answer:
To detect if the call on the controller is “POST” action or a “GET” action we can use “Request. HTTPMethod” property as shown in the below code snippet.

public ActionResult SomeAction()
{
      if (Request.HTTPMethod == "POST")
      {
           return View("SomePage");
      }
      else
      {
      return View("SomeOtherPage");
      }
}

Question 51.
What is bundling and minification in MVC?
Answer:
Bundling and minification help us to improve request load time of a page thus increasing performance How does bundling increase performance?

Web projects always need CSS (Cascading Style Sheet) and script files. Bundling helps us to combine to multiple JavaScript and CSS file into a single entity thus minimizing multiple requests into a single request.

For example consider the below Web request to a page. This page consumes two JavaScript files “JavaScriptljs” and “JavaScript2.js”. So when this is page is requested it makes three request calls as shown in Figure 6.25:

  • One for the “Index” page.
  • Two requests for the other two JavaScript files “JavaScriptl .js” and “JavaScript2.js”.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 26

Below scenario can become worst if we have lot of JavaScript files resulting in many multiple requests thus decreasing performance. If we can somehow combine all the JS files into a single bundle and request them as a single unit that would result in increased performance. (See the Figure 6.26 which has a single request.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 27

Question 52.
So how do we implement bundling in MVC?
Answer:
Open the “BundleConfig.es” from the “App Start” folder as shown in Figure 6.27.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 28

In the “BundleConfig.es” add the JS files which you want bundle into single entity form the bundles collection. In the below code we are combining all the JavaScript JS files which are existing in the “Scripts” folder as a single unit in to the bundle collection.

bundles.Add(new ScriptBundle(“~/Scripts/MyScripts”).lnclude(
“-/Scripts/*.js”));

Below is how your “BundleConfig.es” file will look like.

public class BundleConfig
{
       public static void RegisterBundles(BundleCollection bundles)
       {
              bundles.Add(new ScriptBundle("-/Scripts/MyScripts").Include( . "-/Scripts/*.j s"));
              BundleTable.EnableOptimizations = true;
      }
}

Once you have combined your scripts into one single unit we then to include all the JS files in to the view using the below code. The below code needs to put in the ASPX (Active Server Page Extended) or RAZOR view.
Razor is an ASP.NET programming syntax used to create dynamic’Web page with the C# or Visual Basic.

<%= Scripts.Render(“~/Scripts/MyScripts”) %>

If you now see your page requests you would see that script request is combined into a one request (See Figure 6.26).

Question 53.
How can you test bundling in debug mode?
Answer:
If you are in a debug mode you need to set “EnableOptimizations” to true in the “bundleconfig.es” file or else you will not see the bundling effect in the page requests.

BundleTable.EnableOptimizations = true;

Question 54.
Explain minification and how to implement the same.
Answer:
Minification reduces the size of script and CSS files by removing blankspaces, comments, etc. For example below is a simple JavaScript code with comments.

// This is test 
var x=0; 
x = x + 1; 
x = x * 2 ;

After implementing minification the JavaScript code looks something as below. You can see how whitespaces and comments are removed to minimize file size and thus increasing performance.

var x=0;x=x+ 1;x=x*2;

Question 55.
How to implement minification?
Answer:
When you implement bundling minification is implemented by itself. In other words steps to implement bundling and minification are same.

Question 56.
Explain the concept of View Model in MVC.
Answer:
A view model is a simple class which represents data to be displayed on the view.

For example below is a simple Customer model object with “CustomerName” and “Amount”
properties.

CustomerViewModel pbj = new CustomerViewModel(); 
obj.Customer.CustomerName = "Shiv";
obj.Customer,Amount = 1000;

But when this “Customer” model object is displayed on the MVC view it looks something as shown in the Figure 6.28. It has “CustomerName”, “Amount” plus “Customer buying level” fields on the view / screen as shown in Figure 6.28. “Customer buying level” is a color indication which indicates how aggressive the customer is buying.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 29

“Customer buying level” color depends on the value of the “Amount property. If the amount is greater than 2000 then color is red, if amount is greater than 1500 then color is orange or else the color is yellow.
In other words “Customer buying level” is an extra property which is calculated on the basis of Amount.
So the CustomerViewModel class has three properties as summarized in Table 6.1.

  • “TxtCustomerName” textbox takes data from “CustomerName” property as it is.
  • “TxtAmount” textbox takes data from “Amount” property of model as it is.
  • “CustomerBuyingLevelColor” displays color value depending on the “Amount” value.
Customer Model Customer View Model
Customer Name TXt Customer Name
Amount TXt Amount

Customer Buying Levelcolor

Question 57.
How can we use two ( multiple) models with a single view?
ANswer:
Let us first try to understand what the interviewer is asking. When we bind a model with a view we use the model drop-down as shown in the Figure 6.29. In the Figure we can only select one model.
But what if we want to bind “Customer” class as well as “Order” class to the view.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 30

For that we need to create a view model which aggregates both the classes as shown in the below code. And then bind that view model with the view.

public class CustOrderVM 
{
        public Customer cust = new Customer( ); 
        public Order Ord = new Order();
} 

In the view we can refer both the model using the view model as shown in the below code.

<%= model.oust.Name %>
<%- model. Ord.Number %>

Question 58.
What kind of logic view model class will have?
Answer:
As the name says view model this class has the gel code (Bridge Code) or connection code which connects the view and the model. So the view model class can have following kind of logics:

• Color transformation logic: For example you have a “Grade” property in model and you would like your Ul (User Interface) to display “red” color for high-level grade, “yellow” color for low-level grade and “green” color of OK grade.

• Data format transformation logic: Your model has a property “Status” with “Married” and “Unmarried” value. In the Ul you would like to display it as a checkbox which is checked if “married” and unchecked if “unmarried”.

• Aggregation logic: You have two different Customer and Address model classes and you have view which displays both “Customer” and “Address” data on one go.

• Structure downsizing: You have “Customer” model with “CustomerCode” and “CustomerName” and you want to display just “CustomerName”. So you can create a wrapper around model and expose the necessary properties.

Question 59.
What is the use of “AllowHTML” and “Validatelnput” attributes?
Answer:
While working with MVC you may have noticed that MVC actions doesn’t allow posting HTML (HyperText Markup Language) values. This is done to avoid cross site scripting security issues. Look at the example given in Figure 6.30 where we are trying to post HTML to the MVC action.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 31

But you can bypass this restriction by using one of the following two attributes:
1. Validatelnput attribute at controller level or action level (See Figure 6.31).

[HttpPost()]
[Validatelnput(false)]
public ActionKesult Index(ArticleData o)
{
return View(o);
}

2. AllowHtml attribute at mode level (See Figure 6.32).

public claw* .ArticleOsta
{
, [AllowHtffllO )
public string ArticleContent { get; set; } public string ArticleTitle { get; set; }
}

Question 60.
Explain unobtrusive JavaScript.
Answer:
Unobtrusive JavaScript helps you to decouple presentation and behavior. Consider the below button code it has two parts: one is the Ul, i.e., the button itself and second is the behavior, i.e., “ShowAlert () “.
In other words the button is tied up with the “ShowAlert” action. It would be great if we could decoup’– the behavior from the button so that any other behavior can be attached with the button.

<input type="button" onclick="ShowAlert()" id="btn" />
<script>
function ShowAlert( )
{
       alert("Hello");
}
</script>

Look at this button code you can see no action is attached with the below button element.

<input type=”button ” id= ”btn ” />

Action to the button is attached on runtime as shown in the below code. If needed tomorrow we can attach some other behavior with “btn” button. So unobtrusive JavaScript is nothing but decoupling the presentation from the behavior.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 32

<script>
function ShowAlert()
{
alert("Hello");
}
var el =
document.getElementByld("btn");
el.onclick = ShowAlert;
</script>

Question 61.
Explain the need of display mode in MVC?
Answer:
Display mode displays views depending on the device the user has logged in with. So we can create different views for different devices anddisplay mode will handle the rest.

For example we can create a view “Home.aspx” which will render for the desktop computers and Home.Mobile.aspx for mobile devices as shown in Figure 6.33. Now when an end user sends a request to the MVC application, display mode checks the “user agent” headers and renders the appropriate view to the device accordingly.

Question 62.
How can we validate using Facebook or Twitter accounts (MVC OAuth)?
Answer:
One of the most boring processes for an end user is registering on a site. Sometimes those long forms and e-mail validation just puts off the user. So how about making things easy by validating the users using their existing Facebook, Twitter, Linkedin, etc., accounts. So the user uses something which he/she already has while the site is assured that this user is an authorized user.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 33

This is achieved by using MVC OAuth (Open Standard for Authorization).
Using MVC 0 Auth is a three step process:

  • Register your MVC application / Website with the external site, i.e., facebook, twitter, etc. Once you register your app you get an ID and key from the external site. Figure 6.35 shows how Facebook gives the App ID and Key. In Facebook they term the key as the “App Secret”. This process varies from site to site. So Facebook can have X steps while Twitter can X+1.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 34

  • Next step is to open “AuthConfig.es” and you will see lot of readymade code to user your ID and Key. So use the appropriate method as per site, and provide the ID and Key.
OAuthWebSecurity.RegisterMicrosoftClient( 
       clientld: 
       clientSecret:
OAuthWebSecurity.RegisterTwitterClient(
      consumerKey: "" , 
      consumerSecret: " ");
OAuthWebSecurity.RegisterFacebookClient(
       appld: " ",
       appSecret: "");
OAuthWebSecurity.RegisterGoogleClient( );
  • Now if you run your application you should get a link to Facebook login as shown in the Figure 6.36. So if you login in Facebook it will redirect to your MVC application.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 35

Question 63.
What is the use of ActionName in MVC?
Answer:
Answered in the next question.

Question 64.
Can we overload Actions / Controllers in MVC?
Answer:
Let us first try to understand what interviewer is asking. If you have a controller as shown in the below code snippet and in the controller if you have overloaded methods will it work. For example in the below “Customer” controller we have two “LoadCustomer {)” methods one with a parameter and one without a parameter.
So will this work. The answer is No.

public class CustomerController: Controller
{
     //
    // GET: /Customer/
    public ActionResult LoadCustomer( )
    {
          return Content("LoadCustomer");
    }
    public ActionResult LoadCustomer(string str)
    {
          return Content("LoadCustomer with a string");
    }
}

If you try to invoked “LoadCustomer” you get an error as shown in Figure 6.37.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 36

In order to resolve the same you decorate one of your actions with “ActionName” attribute as shown in the below code.

public class CustomerController: Controller
{
       //
      // GET: /Customer/
      public ActionResult LoadCustomer( )
      {
           return Content("LoadCustomer");
      }
      [ActionName("LoadCustomerbyName")]
      public ActionResult LoadCustomer(string str)
      {
            return Content("LoadCustomer with a string");
      }
}

So now if you make a call to URL (Uniform Resource Locator) “Customer/LoadCustomer” the “LoadCustomer” action yvill be invoked and with URL structure “Customer/ LoadCustomerByName” the “LoadCustomer (string str) * will be invoked.

Question 65.
How can we do exception handling in MVC?
Answer:
There are six ways by which you can achieve exception handling in MVC.

Method 1: Simple way
The simplest way is to use the traditional .NET exception handling style, i.e., try and catch block. Now when exception happens catch block gets executed and it redirects to the error view.
But if we use this method then we will not be utilizing MVC exception mechanism properly and completely. In the further sections we will discuss five important ways by which we can utilize MVC provided features for exception handling.

public ActionResult SomeKrror()
{
      try
      ( )
      catch(Exception ex)
      {return View("Error");}
}

Method 2: Override “OnException” method

In this method we can override the “OnException” event and set the “Result” to the view name. This view gets invoked when error occurs in this controller. In the below code you can see we have set the “Result” to a view named as “Error”.
We have also set the exception so that it can be displayed inside the view.

public class HomeController: Controller
{
       protected override void OnException(ExceptionContext filterContext)
       {
            Exception ex = filterContext.Exception;
            filterContext.ExceptionHandled = true;
          
            var model = new HandleErrorlnfo(filterContext.Exception,
            "Controller", "Action");

            filterContext.Result = new ViewResult( )
            {
                    ViewName = "Error",
                    ViewData = new ViewDataDictionary(model)
            };
      }
}

To display the above error in view we can use the below code:

@Model. Exception;

The problem with this approach is we cannot reuse the error handling logic across multiple controllers. ‘

Method 3: Using nHandleError” Attribute
The other way of handling error is using “HandleError” attribute. Implementing “HandleError” attribute is a two-step process:
Step 1: We need to first decorate the action method with “HandleError” attribute as shown in the below code.

public class HomeController: Controller
{
         [HandleError()]
          public ActionResult SomeErrorf)
          {
                 throw new Exception("test");
          }
}

Step 2: In the “Web.config” file you need to add the “customErrors” tag and point to the “Error” view as shown in the below “Web.config” code snippet.

<system.Web>
<customErrors defaultRedirect="Error.cshtml" mode="On">
</customErrors>
</system.Web>

In case you want different error views for different exception types you can decorate action method with multiple “HandleError” attribute point to multiple views as per exception types.

public class HomeController: Controller
{
       [HandleError(ExceptionType=typeof(ArithmeticException), 
       View="Arthimetic")]
       [HandleError(ExceptionType = typeof(NotlmplementedException), View ="Error1")]
       public ActionResult SomeError( )
       {
       }
}

Method 4: Inheriting from nHandleErrorAttribute”
One of the biggest drawbacks of all the previous method was reusability. Error handling logic cannot be reused across other controllers.
In order to reuse error handling logic across controller we can inherit from “HandleErrorAttribute” class and decorate this class as attribute across controller.

public class Err: HandleErrorAttribute
{
       public override void OnException(ExceptionContext filterContext)
       {
              Exception ex = filterContext.Exception;
              filterContext.ExceptionHandled = true; '
              var model = new HandleErrorInfo(filterContext.Exception, 
              "Controller", "Action");

              filterContext.Result = new ViewResult( )
              {
                      ViewName = "Error1",
                      ViewData = new ViewDataDictionary(model)
              };
       }
}

Method 5: Handling HTTP errors
All MVC exception handling techniques discussed till now do not handle HTTP (HyperText Transfer Protocol) errors like file not found, HTTP 500 error, (Internal Server Error) etc. For that we need to make an entry of the error action and the error status code as shown in the below config file.

<system.Web> 
<customErrors
            mode="On" defaultRedirect="Error1">
<error statusCode="404" redirect="~/Testing/NoPageFound"/>
</customErrors>
</system.Web>

Method 6: Global Error handling in MVC
If you wish to do global error handling across your application you can override the “Application_Error” event and do a Response .Redirect from the global error event. So if the error handling is not done at the controller level it will get propagated to “Global.asax” file.

public class MvcApplication: System.Web.HTTPApplication
{
       protected void Application_Error(object sender, EventArgs e)
       {
              Exception exception = Server.GetLastError( );
              Server.ClearError( );
              Response.Redirect("/Home/Error");
       }
}

The best is combination of “Method 4” and “Method 6”. Create error handling classes which inherit from “HandleError At tribute” class and decorate them respectively on controllers and action methods. So this takes care of errors happening on controllers and actions.
As a safety enable Global error handling as a fallback for any unexpected and unhandled errors by using ”Appiication_Error” event as described in “Method 6”.

Question 66.
How to handle multiple Submit buttons in MVC?
Answer:
Let us elaborate on what the interviewer is asking.
Take a scenario where you have a view with two Submit buttons as shown in the below code.

<form action="Actionl" method=post> 
<input type="submit" name="Submitl"/>
<input type="submit" name="Submit2"> .
</form>

In the above code when the end user clicks on any of the Submit buttons it will make a HTTP POST to “Action 1”;
The question from the interviewer is:
“What if we have want that on “SubmitT’ button click it should invoke “Actionl” and on the “Submit2” button click it should invoke “Action2”.”
There are three basic approaches to solve the above problem scenario.
Using HTML:
In the HTML way we need to create two forms and place the “Submit” button inside each of the forms. And every form’s action will point to different / respective actions. You can see the below code the first form is posting to “Actionl” and the second form will post to “Action2” depending on which “Submit” button is clicked.

<form action="Action1" method=post> 
<input type="submit" name="Submit1"/>
</form> 
<form action="Action2" method=post>
<input type="submit" name="Submit2">
</form>

Using Ajax:
In case the interviewer complains that the above approach is not Ajax, this is where the second approach comes into picture. In the Ajax way we can create two different functions “Funl” and “Funl”, see the below code. These functions will make Ajax calls by using jQuery or any other framework. Each of these functions are binded with the “Submit” button’s “OnClick” events.

<Script language="javascript">
function Fun1( )
{
      $.post("/Action1", null, CallBack1);
}
function Fun2( )
{
      $.post("/Action2", null, CallBack2);
}
</Script>
<form action="/Action1" method=post>
<input type=submit name=sub1 onclick="Fun2( )"/>
</form>
<form action="/Action2" method=post>
<input type=submit name=sub2 onclick="Funl()"/>
</form>

Using “ActionNameSelectorAttribute”:
This is a great and a clean option. The “ActionNameSelectorAttribute” is a simple attribute class where we can write decision making logic which will decide which action can be executed.
So the first thing is in HTML we need to put proper name’s to the Submit buttons for identifying them on the server.

You can see we have put “Save.” and “Delete” to the button names. Also you can notice in the action we have just put controller name “Customer” and not a particular action name. We expect the action name will be decided by “ActionNameSelectorAttribute”.

<form action="Customer" method=post>
<input type=submit value="Save" name="Save" /xbr />
<input type=submit value="Delete" name="Delete"/>
</form>

So when the Submit button is clicked, it first hits the “ActionNameSelector” attribute and then depending on which submit is fired it invokes the appropriate action as shown in Figure 6.38.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 37

So the first step is to create a class which inherits from “ActionNameSelectorAttribute” class. In this class we have created a simple property “Name”.
We also need to override the “isValidName” function which returns true orflase. This function is where we write the logic whether an action has to be executed or not. So if this function returns true then the action is executed or else it is not.

public class SubmitButtonSelector: ActionNameSelectorAttribute
{
       public string Name { get; set; }
       public override bool IsValidName(ControllerContext controllerContext, 
       string actionName, System.Reflection.Methodlnfo methodlnfo)
{
       // Try to find out if the name exists in the data sent from form
       var value =
       controllerContext.Controller.ValueProvider.GetValue(Name); 
       if (value != null)
       {
              return true;
       }
       return false;
    }
}

The main part of the above function is in the below code. The “ValueProvider” collection has all the data that has been posted from the form. So it first looks up the “Name” value and if its found in the HTTP request it returns true or else it returns false.

var value = controllerContext.Controller.ValueProvider.GetValue(Name); if (value != null)
{
       return true;
}
return false;

This attribute class can then decorated on the respective action and the respective “Name” value can be provided. So if the Submit is hitting this action and if the name matches of the HTML Submit button name it then executes the action further or else it does not.

public class CustomerController: Controller
{
       [SubmitButtonSelector(Name="Save")]
       public ActionResult Save( )
       {
      return Content("Save Called");
     }
       [SubmitButtonSelector(Name = "Delete")]
        public ActionResult Delete()
      {
            return Content("Delete Called");
     }
}

Question 67.
What is the of AntiForgery token in MVC?
Answer:
Please read the next answer for the same.

Question 68.
What is CSRF attack and how can we prevent the same in MVC?
Answer:
CSRF stands for Cross Site Request Forgery. So if you see the dictonary meaning of forgery:
“It’s an act of copying or imitatingthings like signature on a cheque, official documents to deceive the authority source for financial gains. ”
So when it comes to Website this forgery is termed as CSRF (Cross Site Request Forgery).

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 38

CSRF is a method of attacking/hacking a Website where the attacker imitates a.k.a forges as a trusted source and sends data to the site. Genuine site processes the information innocently thinking that data is coming from a trusted source.
For example, consider the Figure 6.39 which shows a screen of an online bank. End user uses this screen to transfer money.
Below is a forged site created by an attacker which looks a game site from outside, but internally it hits the bank site for money transfer as shown in Figure 6.40.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 39

The internal HTML of the forged site has those hidden fields which have the account number and amount to do transfer money.

<div> 
Win 1000000 US$
<form action="HTTP: //localhost: 23936/Genuine/Transfer" method=post> 
<input type=hidden name="amount" value="10000” />
<input type=hidden name="account" value="3002" />
<input type=submit value="Play the ultimate game" />
</form>
</div>

Now let’s say the user has logged in to the genuine bank site and the attacker sent this forged game link to his/her e-mail. The end user thinking that it’s a game site clicks on the “Play the ultimate game” button and internally the malicious code does the money transfer process as shown in Figure 6.41.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 40

So a proper solution to this issue can be solved by using tokens as shown in Figure 6.42.

  • End user browses to the screen of the money transfer. Before the screen is served server injects a secret token inside the HTML screen in form of a hidden field.
  • Now hence forth when the end user sends request back he/she has to always send the secret token. This token is validated on the server.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 41

Implementing token is a two-stap process in MVC.

First apply “ValidateAntiForgeryToken” attribute on the action.
[ValidateAntiForgeryToken]

public ActionResult Transfer()
{
      // password sending logic will be here
      return Content(Request.Form["amount"] +
      " has been transferred to account "
      + Request.-Form["account"]) ;
}

Second in the HTML Ul screen call “@Html. AntiForgeryToken ()” to generate the token.

<div>
        Transfer money
<form action="Transfer" method=post>
       Enter Amount
<input type="text" name="amount" value="" /><br />
      Enter Account number
<input type="text" name="account" value='"' /><br />
      @Html.AntiForgeryToken()
<input type=submit value="transfer money" />
</form>
</div>

So now henceforth when any untrusted source sends a request to the server it would give the forgery errors ash shown in Figure 6.43.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 42

If you do a view source of the HTML you would find the below verification token hidden field with the secret key.

<input name=" RequestVerificationToken" type="hidden"
value="7iUdhsDNpEwiZFTYrH5kp/q7j L0sZz+CSBh8mb2ebwvxMJ3eYmUZXp+uofko6ei PDO 
fmC7Q0o4SXeGgRpxFp0i+Hx3 fgVlVybgCYpyhFw5IRyYhNqi9KyH0 seOhBPRu/ 9kYwEXXnVGB9ggdXCVP 
clud/gUzjWVCvUlQxGA9dKPA=" />

Question 69.
What is XSS?
Answer:
XSS (Cross Site Scripting) is a security attack where the attacker injects malicious code while doing data entry. This code can be a JavaScript, VBScript or any other scripting code. Once the code is injected in end user’s browser. This code can run and gain access to cookies, sessions, local files and so on.

For instance Figure 6.44 shows a simple product data entry form. You can see in the product description how the attacker has injected a JavaScript code.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 43

Once we click submit you can see the JavaScript code actually running as shown in Figure 6.45.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 44

Question 70.
How can we prevent the same in MVC?
Answer:
In MVC by default XSS attack is validated. So if any one tries to post JavaScript or HTML code he she gets an error as shown in Figure 6.46.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 45

Question 71.
What is the difference between “Validatelnput” and “AllowHTML” in MVC?
Answer:
As said in the previous question in ASP.NET MVC we are not allowed to postscripts and HTML code by default. But consider the situation as shown in Figure 6.47 where we want HTML to be written and submitted.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 46

The other scenario where we need HTML to be posted is HTML editors. So there is always a need now and then to post HTML to the server.
So for those kinds of scenarios where we want HTML to be posted we can decorate the action with “Validateinput” set to false. This bypasses the HTML and Script tag checks for that action.
You can see in the below code we have requested the MVC framework to not validate the input to the action.

[Validatelnput(false)]
public ActionResult PostProduct(Product obj)
{
return View(obj);
}

But the above solution is not proper and neat. It opens a complete Pandora box of security issues. In this product screen scenario we just HTML in product description and not in product name as shown in Figure 648.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 47

But because we have now decorated validate false at the action level, you can also write HTML in product name field as well.

That’s where “AHOWHTML” comes to help. You can see in the below code we have just decorated the “ProductDescription” property .

public class Product
{
      public string ProductName { get; set; }
      [AllowHtm1]
      public string ProductDescription { get; set; }
}

And from the action we have removed "Validatelnput" attribute.

public ActionResult PostProduct(Product obj)
{
      return View(obj);
}

If you now try to post HTML in product tags in product name field you will get an error saying you cannot post HTML as shown in Figure 6.49.

ASP.NET MVC (Model View Controller) Interview Questions in . NET chapter 6 img 48

So the difference between Validatelnput and AllowHtml is the granularity of preventing XSS attacks.
Below are some more practical questions which are asked frequently. I am thankful to Mr Lalit Kale ( HTTPs: // lalitkale.wordpress.com/) to collect the same and put it forward.

How MVC helps in unit testing while traditional ASP.NET does not?
What are extensibility features ofASP.NET mvc?
What are child actions?
What is the difference between layout and master pages?
How you can plug-in your favorite. loC (Inversion of Container) container in MVC? (7-10 years exp) What are the disadvantages of using ASP.NET MVC?
When you will suggest ASP.NET Webform should be used and when you will recommend ASP.NET MVC? (architect question)
In your opinion, what is the best way, you can use ASP.NET MVC with WCF? (architect and open ended question)

Getting started with .NET and MVC Videos

We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

Getting started with .NET and MVC Videos

Every time I update my edition, I always want to do something crazy for my readers. Here’s one awesome gift you get with this book. Learn .NET and MVC for free. With this book, you will get a DVD (Digital Video/Versatile Disk) which has the below videos which help you to learn .NET and MVC absolutely free. So enjoy the video series created by me personally. Below is the complete list of video indexes.

Learn .NET in 60 days

(Day 1 )Lab 1: Creating your first program

(Day 1) Lab 2: Creating your first program

(Day 1) Lab 3: Integer DataType

(Day 1) Lab 4: Exception Handling

(Day 1) Lab 5: IF Condition, Return Try/Catch

(Day 2) Lab 6: Commenting

(Day 2) Lab 7: For Loop

(Day 2) Lab 8: Simple calculator program

(Day 3 )Lab 9: Creating Your First Application

(Day 3) Lab 10: Creating the Customer Screen

(Day 4) Lab 11: Displaying Customer Screen

(Day 4) Lab 12: Multiple Document Interface(MDI)

(Day 5) Lab 13: Classes & Objects

(Day 6) Lab 14: Getting Data from SQL Server

(Day 7) Lab 15: Inserting data into SQL Server

(Day 7) Lab 16: Connection string in App.config

(Day 8) Lab 17: Delete Functionality

(Day 9) Lab 18: Update Functionality

(Day 9) Lab 19: 2 Tier Architecture

(Day 10) Lab 20: Creating a Web application

(Day 10) Lab 21: Connect app to DAL

(Day 11 and 12) Lab 22: Insert, Update and

Delete

(Day 13) Lab 23: Implementing 3 Tier Architecture

(Day 14) Lab 24: Security

(Day 15) Lab 25: Web Security

(Day 16) Lab 26: REGEX

(Day 17) Lab 27: Improving Database Design

(Day 18) Lab 28:1 to many relationship

(Day 19) Lab 29:1 to Many(lnsert)

(Day 20) Lab 30:1 to Many(Select and Delete) (Day 21) Lab 31:1 to Many(Update)

(Day 22) Lab 32: Stored Procedure Day 23 to Day 60: Project

Learn MVC Step-by-Step
Learn MVC 5 Step-by-Step Lab 1: Simple Hello world.
Lab 2: Explain MVC Routing.
Lab 3: Explain ViewData, ViewBag, TempData, and Session.
Lab 4: Explain Model and Strongly typed views.
Lab 5: Explain Model Binders.

 

.NET & MVC Videos Interview Questions in . NET chapter 22 img 1

It’s very important during interview to be clear about what position you are targeting. Depending on what positions you are targeting the interviewer shoots you questions. Example if,you are looking for a project manager position you will be asked around 20% technical questions and 80% management.

Note: In small scale software house and mid scale software companies there are chances where they expect 
a PM to be very much technical. But in big software houses the situations are very much different, interview 
are conducted according to positions.... Unless the interviewer changes the rule.

Figure 22,1 shows a general hierarchy across most IT companies.

Note: There are many small and medium software companies which do not follow this hierarchy 
and they have there own adhoc way of defining positions in the company.

So why is the need of hierarchy in a interview.

“Interview is a contract between the employer and candidate to achieve specific goals. ”

So employer is looking for a suitable candidate and candidate looks for a better career. Normally in interviews, the employer is very clear about what type of candidate he/she is looking for. However, 90% times the candidate is not clear about the positions he/she is looking for.

How many times it has happened with you that you have given a whole interview and when you mentioned the position you are looking for…pat comes the answer, “ we do not have any requirements for this position”. So be clarified about the position right from when you start the interview.

Following are the number of years of experience according to position.

  • Junior engineers are especially freshers and work under software engineers.
  • Software engineers have around 1 to 2 years of experience. Interviewer expects software engineers to be technically at a medium level.
  • Senior Software Engineers have around 2 to 4 years of experience. Interviewer expects them to technically be very strong.
  • Project leads should handle majority technical aspect of project and should have around 4 to 8 years of experience. They are also indirect architect of the project. Interviewer expects them to be technically strong so that they can drive the architecture part of the project. Interviewer also expects them to have people management skills.
  • Project Manager are expected to be around 40% technically strong and should have experience above 10 years plus. But they are more interviewed from aspect of project management, client interaction, people management, proposal preparation, etc.

So now judge where you stand, and where you want to go

Resume Preparation Guidelines

First impression the last impression
Note: A sample resume is provided in “SampleResume” folder.

Before even the interviewer meets you he will first meet your resume. Interviewer looking at your resume is almost a 20% interview happening without you knowing it. I was always a bad guy when it comes to resume preparation. But when I looked at my friends resume they where really good. Now that I am writing series of book on interviews I thought this will be a good point to put in. You can happily skip it if you are confident about your resume. There is no hard and fast rule that you have to follow the same pattern but just see if these all check list are attended.

  • Use plain text when you are sending resumes through e-mail. For instance you sent your resume using Microsoft Word and what if the interviewer is using Linux he will never be able to read your resume. You cannot be sure both wise, you sent your resume in Word 2000 and the guy has Word 97…uuhhh.
  • Attach a covering letter it reaily impresses and makes you look traditionally formal. Yes, even if you are sending your CV through e-mail send a covering letter.

Check list of content you should have in your resume:

  • Start with an objective or summary, for instance, “Working as a Senior Database administrator for more than 4 years. Implemented quality Web-based application. Follow the industry’s best practices and adhered to and implemented processes, which enhanced the quality of technical delivery. Pledge to deliver the best technical solutions to the industry.”
  • Specify your Core strengths at the start of the resume by which the interviewer can make a quick decision are you eligible for the position. For example:

o Looked after data mining and data warehousing department independently. Played a major role in query optimization.
o Worked extensively in database design and ER (Entity Relationship) diagram implementation.
o Well versed with CMMI (Capability Maturity Model Integration) process and followed it extensively in projects.
o Looking forward to work in a project manager or senior manager position.

This is also a good position to specify your objective or position which makes it clear to the interviewer that should he call you for an interview. For instance, if you are looking for senior positions specify it explicitly ‘looking for this job profile’. Any kind of certification like MCP (Microsoft Certified Professional), MCSD (Microsoft Certified Systems Engineer), etc., you can make it visible in this section.

Once you have specified briefly your goals and what you have done its time to specify what type of technology you have worked with. For instance RDBMS (Relational Database Management System), Tools, Languages, Web servers, process (Six sigma, CMMI).

  • After that you can make a run-through of your experience company-wise that is what company you have worked with, year/month joining and year/month left. This will give an overview to the interviewer what type of companies you have associated your self.

Now its time to mention all the projects you have worked on till now. The best is to start in descending order that is from your current project and go backward. For every project try to put these things:

  • Project Name / Client name (It’s sometimes unethical to mention the client’s name; I leave it to the readers).
  • A number of team members.
  • The timespan of the project.
  • Tools, language, RDBMS, and technology were used to complete the project.
  • Brief summary of the project.

Senior people who have huge experience will tend to increase their CV (Curriculum Vitae) by putting in summary for all projects. The best for them is to just put descriptions of the first three projects in descending manner and rest they can say verbally during the interview. I have seen my CV above 15 pages… I doubt who can read it.

  • Finally comes your education and personal details.
  • Trying for onsite, do not forget to mention your passport number.
  • Some guys tend to make their CV large and huge. I think an optimal size should be no more than 4 to 5 pages.
  • Do not mention your salary in your CV. You can talk about it during an interview with HR (Human Resources) or the interviewer.
  • When you are writing your summary for the project make it effective by using verbs like managing a team of 5 members, architected the project from start to finish, etc. It brings huge weight.
  • This is essential to take 4 to 5 Xerox copies of your resume you will need it now and then.
  • Just in case take at least 2 passport photos with you. You can escape it but many times you will need it.
  • Carry all your current office documents especially your salary slips and joining letter.

Salary Negotiation

Ok, that’s what we all do it for MONEY… not everyone but still, money means a lot. This is probably the weakest area for techno-savvy guys. They are not good negotiators. I have seen so many guys at the first instance they will smile and say “NEGOTIABLE SIR”.

So here are some points:

1. Do a study of what is the salary trend? For instance, have some kind of baseline. For example, what is the salary trend on the number of years of experience? Discuss this with your friends out.

2. Do not mention your expected salary on the resume?

3. Let the employer first make the salary offer. Try to delay the salary discussion till the end.

4. If they say what you expect? Come with a figure with a little higher-end and say negotiable. Remember never say negotiable on something which you have aimed, HR persons will always bring it down. So negotiate on AIMED SALARY plus something extra.

5. The normal trend is that they look at your current salary and add a little it so that they can pull you in. Do your homework my salary is this much and I expect this much so whatever it is now I will not come below this.

6. Do not be harsh during salary negotiations.

7. It’s good to aim high. For instance, I want 1 billion dollars/month but at the same time be realistic.

8. Some companies have those hidden costs attached in salary clarify it rather than be surprised at the first salary package.

9. Many of the companies add extra performance compensation in your basic which can be surprising at times. So have a detailed breakdown. The best is to discuss on-hand salary rather than NET or CTC (Cost to Company).

10. Talk with the employer about what frequency does the hike happens.

11. Take everything in writing, go back to your house, and have a look once with a cool head is the offer worth of what your current employer is giving.

12. Do not forget once you have a job in hand you can come back to your current employer for negotiation.

13. Remember the worst part is cribbing after joining the company that your colleague is getting more. So be careful while interview or be sportive to be a good negotiator in the next interview.

14. One very important thing is that the best negotiation ground is not the new company where you are going but the old company which you are leaving. So once you have offered on hand get back to your old employee and show them the offer and then make your next move. It’s my experience that negotiating with the old employer is easy than the new one….Frankly if approached properly rarely anyone will say no as you have spent quite an amount of time with them. Just do not be aggressive or egoistic that you have an offer on hand.

15. Top of all some time some things are worth above money: JOB SATISFACTION. So whatever you negotiate if you think you can get the JOB SATISFACTION aspect on higher grounds go for it. I think it’s worth more than money.

Applicable to Only India

Years of experience Amount in Rupees CTC (Monthly)
Freshers
1 to 2 yrs
4 to 6
6 to 8
8 to 10 yrs
10 to 15 yrs
15 yrs and above
15000 to 20000
25000 to 30000
40000 to 60000
60000 to 70000
70000 to 90000
90000 to 110000110000 and above. Mostly depends on negotiations.

 

Note: The Indian salary card is as per India mega cities like Mumbai, Pune, Banglore, Chennai, 
Hyderabad, Delhi, etc. For mid size cities like Lucknow, Nagpur, Ahmedabad, Amritsar, etc., the CTC will be 15% less.

Applicable to US Only

Years of experience. Amount in Dollars (Yearly)
Fresher’s
2 to 4 yrs
4 to 6 yrs
6 to 8 yrs
8 to 12 yrs
12 and above
45000 to 55000
55000 to 60000
60000 to 65000
70000 to 80000
80000 to 90000
Depends on negotiations

 

 Note: For big cities like NY, Chicago, California state and down town cities the US rated card will be 10% higher.

The scorecard shown above is completely derived from the author’s experience and interaction he had in his circle. It is not an approved scorecard by any authorized body as such and should be taken only as a benchmark to measure your success. Also, note that these rates are applicable for medium and large software companies. Small company rate cards are very irregular and governed by a single owner of the company. So the above rate card is not applicable for small companies. Many people do get mind-blowing salaries even with small experience which again the scorecard does not reflect.

Points to rememberPoints to remember

  • One of the first questions asked during the interview is “Can you say something about yourself?
  • Can you describe yourself and what you have achieved till now?
  • Why do you want to leave your current company?
  • Where do you see yourself after three years?
  • What are your positive and negative points?
  • How much do you rate yourself in .NET and SQL Server in one out of ten?
  • Are you looking for onsite opportunities? (Be careful do not show your desperation of abroad journeys).
  • Why have you changed so many jobs? (Prepare a decent answer do not blame companies and individuals for your frequent change).
  • Never talk for more than 1 minute straight during the interview.
  • Have you worked with the previous version of SQL Server?
  • Would you be interested in a full-time Database Administrator job?
  • Do not mention client names in the resume. If asked say that it’s confidential which brings ahead ^ qualities like honesty
  • When you make your resume keep your recent projects at the top.
  • Find out what the employer is looking for by asking him questions at the start of the interview and I best is before going to the interview. For example if a company has projects on server products employers’ will be looking for BizTalk, CMS (Content Management System), experts.
  • Can you give a brief about your family background?
  • As you are fresher do you think you can really do this job?
  • Have you heard about our company? Say five points about our company? Just read at least once what company you are going for?
  • Can you describe the best project you have worked with?
  • Do you work on Saturday and Sunday?
  • Which is the biggest team size you have worked with?
  • Can you describe the current project you have worked with?
  • How much time will you need to join our organization? What’s the notice period for your current company?
  • What certifications have you cleared?
  • Do you have passport size photos, all academic mark sheets, previous companies’ employment letters, last month’s salary slip, passport, and other necessary documents?
  • What is the most important thing that motivates you?
  • Why do you want to leave the previous organization?
  • Which type of job gives you the greatest satisfaction?
  • What is the type of environment you are looking for?
  • Do you have experience in project management?
  • Do you like to work as a team or as an individual?
  • Describe the best project manager you have worked with?
  • Why should I hire you?
  • Have you been ever fired or forced to resign?
  • Can you explain some important points that you have learned from your past project experiences?
  • Have you gone through some unsuccessful projects, if yes can you explain why did the project fail?
  • Will you be comfortable with the location shift? If you have personal problems say no right at the first .stage…. or else within two months you have to read my book again. ;
  • Do you work late nights? The best answer is if there is a project deadline yes. Do not show that it’s your culture to work during nights.
  • Any special achievements in your life till now…tall your best project which you have done best in your career.
  • Any plans of opening your own software company…Beware do not start pouring your Bill Gate’s
    dream to him can create a wrong impression.

Question 1.
Website references for .NET, ASP.NET, and SQL reading
Answer:
When it comes to interviewing preparation there is no end. Below are some sites which come in very handy for further interview preparation.

www.codeproject.com: This site is owned by Mr. Chris Maunder and has some finest articles on Microsoft programming technologies. I personally write articles on this site a lot.

www.stackoverflow.com: When it comes to programming this site is a savior. Short answers and solutions make it the number one solution site for programmers.

www.dotnetfunda.com: This site belongs to my dearest friend Mr. SheoNarayan and is one the oldest i and finest sites when it comes to .NET and Microsoft technologies.

www.itorian.com/: This site is run by Mr. Abhi Kumar Matsya who is a Microsoft ASP.NET MVP (Model View Presenter) and has some finest articles around ASP.NET and MVC. Do not miss his site it also has lectured in Hindi for programming.

HTTP: //www.kunal-chowdhurv.com/: Started by Mr. Kunal Chowdhury who is a Microsoft MVP (Windows Platform Development). This site has articles around Windows Phone, Silverlight, and Windows 8.

HTTP: //mavurtendulkar.com/: This site comes from Mr. Mayur Tendulkar who is from Pune a Microsoft ^ MVP in windows phone development. We call him the Xamarin guy. If you are looking at mobile development using Microsoft technologies his site is worth a visit.

HTTP: //poojabaraskar.com/: Driven by a young girl Pooja Baraskar this site talks about IOT (Internet ‘ of Things), Gaming and Windows Apps blog. \

HTTP: //csharppulse.Blogspot.in/: This site belongs Mr. Akhil Mittal who resides in Noida and is one ‘ of the very much knows authors on Codeproject and C# corner.

HTTP: //codepattern.net/Bloa/: This site is run by Mr Anil Kumar who is a C# corner MVP and wites ‘ mostly on Microsoft programming technologies.

HTTP: //www.jeanpaulva.com/: This is run by Mr. Jean Paul who is a Microsoft MVP and working as an architect for the past 15 years. The SharePoint and design pattern section of this site is worth looking at. HTTP: //www.f5debug.net/: This is site is run by Mr. Kathik who is a Microsoft ASP.NET MVP. Azure, ‘ Windows phone, and MSBI (Microsoft Business Intelligence) articles are nicely written on this site. –

HTTP: //gaurav-arora.com/: Started by Mr. Gaurav Arora who is from Noida. The articles section of this site has nice articles on C#, Visual Studio, and. NET.

HTTPs: //vivekcek.wordpress.com/: Mr. Vivek who hails from Trivandrum has started this site. It has a nice collection of Azure, C#, .NET, and design pattern sections. This is the only site I saw a dedicated section for TPL (Task Parallel Library).

HTTP: //www.dotnetjalps.com/: Mr. Jalpesh Vadgama who is a Microsoft MVP has started this blog has great articles and videos around C#, ASP.NET, Visual Studio, Architecture, and so on.

HTTP: //www.techmixing.com/: Started by Mr. Vivek Johari Sir, this site talks mostly on SQL Server. . Worth a visit.