ASP.NET 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

Question 1.
What is ASP.Net?
It is a framework developed by Microsoft on which we can develop new generation websites using web forms(aspx), MVC, HTML, Javascript, CSS, etc. Its successor of Microsoft Active Server Pages(ASP). Currently, there is ASP.NET 4.0, which is used to develop websites. There are various page extensions provided by Microsoft that are being used for website development. Eg: aspx, asmx, ascx, ashx, cs, vb, HTML, XML etc.

Question 2.
What are the advantages of ASP.NET?
ASP.Net is the next generation of ASP technology platform. It is superior to ASP in the following ways:

  • Highly Scalable
  • Compiled Code
  • User Authentication
  • Language Support
  • Third-party control
  • Configuration and Deployment are easy,
  • Object and Page caching
  • Strict coding requirements

Question 3.
What’s the use of Response.Output.Write( )?
We can write formatted output using Response.Output.Write( ).

Question 4.
In which event of page cycle is the ViewState available?
After the lnit( ) and before the Page_Load().

Question 5.
What is the difference between Server. Transfer and Response. Redirect?
In Server. Transfer page processing transfers from one page to the other page without making a round-trip back to the client’s browser. This provides a faster response with a little less overhead on the server. The client url history list or current url Server does not update in the case of the Server. Transfer.

Response. Redirect is used to redirect the user’s browser to another page or site. It performs a trip back to the client where the client’s browser is redirected to the new page. The user’s browser history list is updated to reflect the new address.

Question 6.
From which base class all Web Forms are inherited?
Page class.

Question 7.
What are the different validators in ASP.NET?

  1. Required Field Validator
  2. Range Validator
  3. Compare Validator
  4. Custom Validator
  5. Regular expression Validator
  6. Summary Validator

Question 8.
Which validator control do you use if you need to make sure the values in two different controls matched?
Compare Validator control.

Question 9.
What is the concept of Postback in ASP.NET?
Postback is a request which is sent from a client to the server from the same page user is working with. There is an HTTP POST request mechanism in ASP.NET. It posts a complete page back to the server to refresh the whole page.

Question 10.
What is the use of “isPostBack” property?
The “IsPostBack” property of the page object is used to check that the page is posted back or not.

Question 11.
How do you identify that the Page is PostBack?
There is a property named “IsPostBack” property in Post object, which can be checked to know that the page is posted back.

Question 12.
What is ViewState?
ViewState is used to retain the state of server-side objects between page post-backs.

Question 13.
Where the ViewState is stored after the page postback?
ViewState is stored in a hidden field on the page on the client-side. ViewState is transported to the client and back to the server and is not stored on the server or any other external source.

Question 14.
How long the items in ViewState exists?
They exist for the life of the current page.

Question 15.
What are the different Session state management options available in ASP.NET?

  1. In-Process
  2. Out-of-Process.

In-Process stores the session in memory on the web server.
Out-of-Process Session state management stores data in an external server. The external server may be either a SQL Server or a State Server. All objects stored in session are required to be serializable for Out-of-Process state management.

Question 16.
How you can add an event handler?
Using the Attributes property of server side control, e.g.
btnSubmit.Attributes.Add(“onMouseOver,,;,,JavascriptCode( );”)

Question 17.
What is caching?

Caching is a technique used to increase performance by keeping frequently accessed data or files in memory. The request for a cached file/data will be accessed from cache instead of actual location of that file.

Question 18.
what are the main requirements for caching?

  • By caching the response, your request is served by the response already stored in memory.
  • You must be very careful while choosing the items to cache because Caching incurs overhead.
  • A frequently used web form which data doesn’t frequently change is good for caching.
  • A cached web form freezes form?s server-side content, and changes to that content do not appear until the cache is refreshed.

Question 19.
What are the different types of caching?ASP.NET has 3 kinds of caching :

  1. Output Caching,
  2. Fragment Caching,
  3. Data Caching.

Question 20.
Which type if caching will be used if we want to cache the portion of a page instead of whole page?
Fragment Caching: It caches the portion of the page generated by the request. For that, we can create user controls with the below code:
<%@ OutputCache Duration=”120″ VaryByParam=”CategorylD;SelectedlD”%>

Question 21.
List the events in page life cycle.

  1. Page_Prelnit
  2. Page_lnit
  3. Page_lnitComplete
  4. Page_PreLoad
  5. Page_Load
  6. Page_LoadComplete
  7. Page_PreRender
  8. Render

Question 22.
Can we have a web application running without web.Config file?

Question 23.
What is the difference between ASP.NET Webforms and ASP.NET MVC?
ASP.NET Webforms uses the page controller approach for rendering layout. In this approach, every page has its controller.
On the other hand, ASP.NET MVC uses the Front Controller approach. In this approach, there is a common controller for all pages.

Question 24.
Is it possible to create a web application with both webforms and MVC?
Yes. We have to include the below MVC assembly references in the web forms application to create a hybrid application.



System. ComponentModel.DataAnnotations

Question 25.
Can we add code files of different languages in the App_Code folder?
No. The code files must be in the same language to be kept in the App_code folder.

Question 26.
What is Protected Configuration?
It is a feature used to secure connection string information.

Question 27.
Write code to send e-mail from an ASP.NET application?

MailMessage mailMess = new MailMessage ( );
mailMess.From = "
mailMess.To = "";
mailMess.Subject = "Test email";
mailMess.Body = "Hi This is a test mail.";
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send (mailMess);

MailMessage and SmtpMail are classes defined System.Web.Mail namespace.

Question 28.
How can we prevent browser from caching an ASPX page?
We can SetNoStore on HttpCachePolicy object exposed by the Response object’s Cache property:

Response.Cache.SetNoStore ( );
Response.Write (DateTime.Now.ToLongTimeString ());

Question 29.
What is the good practice to implement validations in aspx page?
Client-side validation is the best way to validate data of a web page. It reduces the network traffic and saves server resources.

Question 30.
What is the use of Global.asax file?
The Global.asax file is used to execute the application-level events and sets application- level variables.

Question 31.
What is event bubbling?
When child control sends events to parent, it is termed as event bubbling. Server controls like Data Grid, Data List, and Repeater can have other child controls inside them.

Question 32.
What are the event handlers that we can have in Global.asax file?
Application Events: Application_Start, Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed, Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute,Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache

Session Events: Session_Start,Session_End

Question 33.
Which protocol is used to call a Web service?
HTTP Protocol

Question 34.
Can we have multiple web config files for an application?

Question 35.
What is the difference between web config and machine config?
Web config file is specific to a web application where as machine config is specific to a machine or server. There can be multiple web config files into an application where as we can have only one machine config file on a server.

Question 36.
Explain role based security ?
Role-based security is used in almost all organization, and the Role-based security assigns certain privileges to each role.

  • Each user is assigned a particular role from the list.
  • Privileges as per role restrict the user’s actions on the system and ensure that a user can do only what he is permitted to do on the system.
<AUTHORIZATION>< authorization >
< allow roles="Domain_Name\Administrators" / > < !-- Allow Administrators in domain. 
 — >
< deny users-'*" />                             < !-- Deny anyone else. -- >
< /authorization >

Question 37.
What is Cross Page Posting?
When we click submit button on a web page, the page post the data to the same page. The technique in which we post the data to different pages is called Cross Page posting. This can be achieved by setting POSTBACKURL property of the button that causes the postback. Findcontrol method of PreviousPage can be used to get the posted values on the page to which the page has been posted.

Question 38.
How can we apply Themes to an application?
We can specify the theme in web.config file. Below is the code example to apply the theme:



<pages theme="Windows7" />



Question 39.
What is RedirectPermanent in ASP.Net?
RedirectPermanent Performs a permanent redirection from the requested URL to the specified URL. Once the redirection is done, it also returns 301 Moved Permanently responses.

Question 40.
What is MVC?
MVC is a framework used to create web applications. The web application base builds on Model-View-Controller pattern which separates the application logic from Ul, and the input and events from the user will be controlled by the Controller.

Question 41.
Explain the working of passport authentication.
First of all it checks passport authentication cookie. If the cookie is not available then the application redirects the user to Passport Sign on page. Passport service authenticates the user details on sign on page and if valid then stores the authenticated cookie on client machine and then redirect the user to requested page

Question 42.
What are the advantages of Passport authentication?
All the websites can be accessed using single login credentials. So no need to remember login credentials for each web site.

Users can maintain his/ her information in a single location.

Question 43.
What are the Security Controls?

  • <asp:Login>: Provides a standard login capability that allows the users to enter their credentials
  • <asp:Loginl\lame>: Allows you to display the name of the logged-in user
  • <asp:LoginStatus>: Displays whether the user is authenticated or not
  • <asp:LoginView>: Provides various login views depending on the selected template
  • <asp:PasswordRecovery>: email the users their lost password

Question 44.
How do you register JavaScript for webcontrols ?
We can register javascript for controls using <CONTROL -name>Attribtues.Add(scriptname,scripttext) method.

Question 45.
In which event are the controls fully loaded?
Page load event.

Question 46.
what is boxing and unboxing?
Boxing is assigning a value type to reference type variable. Unboxing is reverse of boxing ie. Assigning reference type variable to value type variable.

Question 47.
Differentiate strong typing and weak typing
In strong typing, the data types of variable are checked at compile time. On the other hand, in case of weak typing the variable data types are checked at runtime. In case of strong typing, there is no chance of compilation error. Scripts use weak typing and hence issues arises at runtime.

Question 48.
How we can force all the validation controls to run?
The Page.Validate( ) method is used to force all the validation controls to run and to perform validation.

Question 49.
List all templates of the Repeater control.

  • ItemTemplate
  • AlternatingltemTemplate
  • SeparatorTemplate
  • HeaderTemplate
  • FooterTemplate

Question 50.
List the major built-in objects in ASP.NET?

  • Application
  • Request
  • Response
  • Server
  • Session
  • Context

Question 51.
What is the appSettings Section in the web.config file?
The appSettings block in the web config file sets the user-defined values for the whole application.
For example, in the following code snippet, the specified Connectionstring section is used throughout the project for database connection:

<add key-'ConnectionString" value="server=local; pwd=password; database=default" /> 

Question 52.
Which data type does the RangeValidator control support?
The data types supported by the RangeValidator control are Integer, Double, String, Currency, and Date.

Question 53.
What is the difference between an HtmllnputCheckBox control and an HtmllnputRadioButton control?
In HtmllnputCheckBoxcontrol, multiple item selection is possible whereas in HtmllnputRadioButton controls, we can select only single item from the group of items.

Question 54.
Which namespaces are necessary to create a localized application?

Question 55.
What is a cookie?
A Cookie is a small piece of information which is stored at the client side. There are two types of cookie:

  • Session/Temporary Cookie: valid for a single session
  • Persistent Cookie: valid for multiple session

Question 56.
What is the default timeout for a cookie?
30 minutes.

Question 57.
How would you turn off cookies on a page of a website?
You have to follow the procedures given below:

  • Use the “Cookie.Discard” property,
  • It gets or sets the discard flag set by the server.
  • When set to true, this property instructs the client application not to save the Cookie on the hard disk of the user at the end of the session.

Question 58.
What are the different types of cookies in ASP.NET?
Session Cookie – Resides on the client machine for a single session until the user does not log out.
Persistent Cookie – Resides on a user’s machine for a period specified for its expiry, such as 10 days, one month, and never.

Question 59.
What is the file extension of web service?
Web services have file extension .asmx..

Question 60.
What are the components of ADO.NET?
The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command, connection.

Question 61.
What is the difference between ExecuteScalar and ExecuteNonQuery?
ExecuteScalar returns output value where as ExecuteNonQuery ctoes not return any value but the number of rows affected by the query. ExecuteScalar used for fetching a single value and ExecuteNonQuery used to execute Insert and Update statements.

Question 62.
What is IIS?
IIS stands for Internet Information Services. It is created by Microsoft to provide Internet-based services to ASP.NET Web applications.

Question 63.
What is the usage of IIS?
Following are the main usage of IIS:

  • IIS is used to make your computer to work as a Web server and provides the functionality to develop and deploy Web applications on the server,
  • IIS handles the request and response cycle on the Web server,
  • IIS also offers the services of SMTP and Frontpage server extensions.
  • The SMTP is used to send emails and use Frontpage server extensions to get the dynamic features of IIS, such as form handler.

Question 64.
What is a multilingual website?
If a website provides content in many languages, it is known as a multilingual website. It contains multiple copies of its content and other resources, such as date and time, in different languages.

Question 65.
What is the parent class of all web server control?
System. Web. Ul.Control class

Question 66.
What is the difference between the GET method () and POST method ()?

Data is affixed to the URL.
Data is not secured.
Data transmission is faster in this method.
It is a single call system.
Only a limited amount of data can be sent.
It is a default method for many browsers.


Data is not affixed to the URL Data is secured.
Data transmission is comparatively slow
It is a two call system
A large amount of data can be sent
It is not set as default. It should be explicitly specified

Question 67.
What is the difference between session object and application object?
The session object is used to maintain the session of each user. A session id is generated if a user enters in the application and when the user leaves the application, the session id is automatically deleted.
On the other hand, the application object is used to store the information and access variables from any page in the application.
Debug class is used to debug builds. Trace class is used for both debug and release builds.

Question 68.
What is the difference between trace and debug?
Debug class is used to debug builds. Trace class is used for both debug and release builds.

Question 69.
What is the difference between client-side and server-side validations in WebPages?
The client-side validation happens at the client’s side with the help of JavaScript and VBScript. This validation has occurred before the Web page is sent to the server. The server-side validation happens at the server side.

Question 70.
What is the difference between file-based dependency and key-based dependency?
File-based dependency: File-based dependency facilitates you to save the dependency on a file in a disk.
Key-based dependency: In key-based dependency, you depend on another cached item.

Question 71.
What is the difference between globalization and localization?
Globalization: Globalization is a technique to identify the part of a Web application that is different for different languages and separate it out from the web application.

Localization: In localization, you try to configure a Web application so that it can be supported for a specific language or locale.

Question 72.
What is the difference between a page theme and a global theme?
Page Theme: The page theme is applied to particular web pages of the project. It is stored inside a subfolder of the App_Themes folder.
Global Theme: The Global theme is applied to all the web applications on the web server. It is stored inside the Themes folder on a Web server.

Question 73.
What is the difference between early binding and late binding?
Early Binding: In early binding, a non-virtual method is called which is decided at a compile time.
Late Binding: In late binding, a virtual method is called which is decided at runtime.

Question 74.
What is the difference between server-side scripting and client-side scripting?
Server-side scripting: In server-side scripting, all the script are executed by the server and interpreted as needed.

Client-side scripting: In client-side scripting, the script will be executed immediately in the browser such as form field validation, email validation, etc. The client-side scripting is usually carried out in VBScript or JavaScript.

Question 75.
How to sign out from forms authentication?
FormsAuthentication.Signout() method is used to sign out from forms authentication.

Question 76.
How to display validation messages in one control?
By the help of ValidationSummary control, we can display all validation messages in one control.

Question 77.
What is the difference between authentication and authorization?
Authentication is a process of identifying user whereas authorization is used to check the access rights of an identified user.

Question 78.
Which object encapsulates state or data of a user?
Session object.

Question 79.
What are the differences between the Response.Write() and Response.Output.Write()?
Response.Write( ) is used for normal output whereas Response.Output.Write() is used for formatted output.

Question 80.
Define the types of configuration files.
There are two types of configuration files:

  • Application Level config = Web.config.
  • Machine Level config = Machine.config.

Question 81.
What is the difference between Web config and Machine config files?
Web config file is specific to web application whereas Machine config file is specific to machine or server.
There can be multiple web config files in an application but only one machine config file.

Question 82.
What are the HTML server controls in ASP.NET?

  • HTML server controls are just like HTML elements that we use on HTML pages.
  • HTML server controls are used to expose properties and events for use.
  • To make these controls programmatically accessible, we specify that the HTML controls act as a server control by adding the runat=Mserver” attribute.

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

Questions 1.
Introduce Yourself?
Freshers: I have pursued my Engineering from Lakshmi Narayan College of Technology, Bhopal which is a prestigious institute in central India. My specialization was Computer Science Engineering.! have knowledge of programming with C# using OOPS concepts and some knowledge with MSSQL as Data Query Language. i have made my Major project using the same technology with the name “Project name”.

Experienced: I have a total experience of 8 years and an overall experience of 7 Years in .NET technology. Throughout my carrier, mostly I have used C# as a programming language using .NET Framework and MSSQL as RDBMS. I also got the chance to work with ASP.NET Webforms applications; MVC Razor-based applications, Web API, and WCF. I have also got experience with Desktop applications using Windows Form and WPF. I have Experienced with design patterns and Agile for Development.! also got the chance to work as Team Lead/Tech lead in the last couple of organizations. Talking about the project domain/types, I have worked with E-gov organizations, E-commerce, product-based, Service-based, Heath Domain, Finance Domain projects.

Note: Customize a bit as per Job Description (JD).

Questions 2.
Explain your Major Project/ Current Project for Experienced Candidates?
Explain the project architecture, team size, your role, and responsibilities in the project.

Questions 3.
What is the reason for the job change?
You need to find the best reason as you already know it deep down. Some reasons can be Late salary payment, Appraisal concerns, unhappiness with the technology you are currently working with, and such reasons.

Questions 4.
What is the reason for the gap/Break-in Education/Experience?
You already know the real reason behind it. Explain the family situations or other reasons that occurred during that time. And at the end don’t forget to mention that everything is well now and you are ready and very enthusiastic about this job.

Questions 5.
Why so many frequent switches?
In case you have switched organizations frequently, be prepared for this question. You need to give the best reasons to support your argument. There may be contractual jobs, explain those contacts or there might be a company that has shut down its operation. So you need to write down a good reason on paper for every switch.

Question 6.
How will berate yourself on a scale of 1-5 in C#
The interviewer may as this question before starting your technical interview. Be careful while rating yourself. Don’t go for 5 unless you are a genius in that particular technology.

Question 7.
Where would you like to see yourself in the next 5 years?
Generally, the interviewer asks this question at the very end of the interview and mostly to freshers. By that time you will get a bit familiar with to interviewer and you will kind of know him/her. Get your answer accordingly. Generally, a Team Lead / Tech Lead is fine to say. You can also go for higher posts like a project manager or further more but be cautious in case your interviewer is too judged type.

Question 8.
Explain any one situation in which you did extraordinary in some project work?
Generally asked experienced candidates. Be ready with a case where you have used some higher concepts and produced some good results which were very unusual. So better be a short storyteller for such questions. It’s just a question to get an idea about you. Be confident and make some notes about it.

UML, Estimation and Project Management 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 UML, Estimation and Project Management

Note: We have released an exclusive book on ‘Architecture Interview questions’ which covers architectur
 in detail. Please e-mail for details.

Question 1.
Explain SOLID principles.
SOLID (Single responsibility, Open-closed, Liskow substitution, Interface Segregation, and Dependency inversion) are five basic principles that help to create good software architecture. SOLID is an acronym where:

• S stands for SRP (Single Responsibility Principle): A class should take care of only one responsibility.
• O stands for OCP (Open Closed Principle): Extension should be preferred over modification.
• L stands for LSP (Liskov Substitution Principle): A parent class object should be able to refer child objects seamlessly during runtime polymorphism.
• I stands for ISP (Interface Segregation Principle): The client should not be forced to use an interface if it does not need it.
• D stands for DIP (Dependency Inversion Principle): High-level modules should not depend on low-level modules but should depend on abstraction.

Question 2.
What are design patterns?
Design patterns are the recurring solutions to recurring problems in software architecture.

Question 3.
Which design patterns have you used in your project?
This question is very subjective as every developer has his own experience. So we will pick up three design patterns, i.e., factory, singleton, and facade, and discuss the same in more depth. In case you are using some other design pattern below is the list with classification, go and pick your best three.
There are three basic classifications of patterns Creational, Structural, and Behavioral patterns.

Creational Patterns

  • Abstract Factory: Create an instance of several families of classes
  • Builder: Separates object construction from its representation
  • Factory Method: Create an instance of several derived classes
  • Prototype: A fully initialized instance to be copied or cloned
  • Singleton: A class in which only a single instance can exist

Structural Patterns

  • Adapter: Match interfaces of different classes.
  • Bridge: Separates an object’s abstraction from its implementation.
  • Composite: A tree structure of simple and composite objects.
  • Decorator: Add responsibilities to objects dynamically.
  • Facade: A single class that represents an entire subsystem.
  • Flyweight: A fine-grained instance used for efficient sharing.
  • Proxy: An object representing another object.

Behavioral Patterns

  • Mediator: Defines simplified communication between classes.
  • Memento: Capture and restore an object’s internal state.
  • Interpreter: A way to include language elements in a program.
  • Iterator: Sequentially access the elements of a collection.
  • Chain of Resp: A way of passing a request between a chain of objects.
  • Command: Encapsulate a command request as an object.
  • State: Alter an object’s behavior when its state changes.
  • Strategy: Encapsulate an algorithm inside a class.
  • Observer: A way of notifying change to a number of classes.
  • Template Method: Defer the exact steps of an algorithm to a subclass.
  • Visitor: Define a new operation to a class without change.

Question 4.
What’s the first step you take for implementing any of the Design Patterns?

Note: In this question the interviewer expects you to give a logical and practical answer. He is trying to
 understand have you really got the concept of design pattern.

Every design pattern solves certain problems. At the end of the day, they are tried and test solutions for a certain architecture problem. So you first need to understand what the problem is and then choose a design pattern accordingly. For instance below are some scenarios where the thought will flow as follows. ,

Problem: You want to create a single instance of an object.
Solution: Singleton design pattern.
Problem: Want to change the behavior of the class without altering the class.
Solution: Decorator pattern.
Problem: Want to loop through a collection without giving him modify access to the collection.
Solution: Iterator pattern.

Question 5.
Can you explain the factory pattern?
Factory pattern is one of the types of creational patterns. You can make out from the name factory itself it’s meant to construct and create something. In the software architecture world, factory pattern is meant to centralize the creation of objects. Below is a code snippet of a client which has different types of invoices. These invoices are created depending on the invoice type specified by the client (See Figure 14.1). There are two issues with the code below:

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 1

  • First, we have lots of ‘new’ keywords scattered in the client, in other ways the client is loaded with a lot of object creational activities which can make the client logic very complicated.
  • The second issue is that the client needs to be aware of all types of invoices. So if we are adding one more invoice class type called ‘InvoiceWithFooter’ we need to reference the new class in the client and recompile the client also.

Taking these issues as our base we will now look into how factory patterns can help us solve the same. Figure 14.2 ‘Factory Pattern’ shows two concrete classes ‘ClsinvoicewithHeader’ and ‘ClsInvoiceWithOutHeader’.

The first issue was that these classes are in direct contact with clients which leads to a lot of ‘new’ keywords scattered in the client code. This is removed by introducing a new class ‘ ClsFactoryinvoice’ which does all the creation of objects.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 2

The second issue was that the client code is aware of both the concrete classes i.e. ‘ClsinvoicewithHeader’ and ‘ClsInvoiceWithOutHeader’. This leads to recompiling of the client code when we add new invoice types. For instance, if we add ‘ClslnvoiceWithFooter’ client code needs to be changed and recompiled accordingly. To remove this issue we have introduced

a common interface ‘Unvoice’. Both the concrete classes ‘ClslnvoiceWithHeader’ and ‘ CisinvoicewithOutHeader’ inherit and implement the ‘Unvoice’ interface.

The client references only the ‘ unvoice’ interface which results in zero connection between the client and the concrete classes (‘ClslnvoiceWithHeader’ and ‘ CisinvoicewithOutHeader’). So now if we add a new concrete invoice class we do not need to change anything on the client side.

in one line the creation of objects is taken care of by ‘cisFactoryinvoice’ and the client disconnection from the concrete classes is taken care of by the ‘ unvoice’ interface.

Below are the code snippets of how the actual factory pattern can be implemented in C#. In order to avoid recompiling the client, we have introduced the invoice interface ‘ unvoice’. Both the concrete classes ‘ClslnvoiceWithOutHeaders ‘ and ‘ClslnvoiceWithHeader’ inherit and implement the ’Unvoice’ interface.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 3

We have also introduced an extra class ‘ CisFactoryinvoice’ with the function ‘ get invoice () ‘ which will generate objects of both the invoices depending on the ‘ intinvoiceType’ value. In short, we have centralized the logic of object creation in the ‘ CisFactoryinvoice’. The client calls the ‘getinvoice’ function to generate the invoice classes. One of the most important points to be noted is that client only refers to ‘ unvoice’ type and the factory class ‘ CisFactoryinvoice’ also gives the same type of reference (See Figure 14.4). This helps the client to be complete detached from the concrete classes, so now when we add new classes and invoice types we do not need to recompile the client.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 4

Question 6.
Can you explain the singleton pattern?
There are situations in a project where we want only one instance of the object to be created and shared between the clients. No client can create an instance of the object from outside. There is only one instance of the class which is shared across the clients. Below are the steps to make a singleton pattern:

  • Define the constructor as private.
  • Define the instances and methods as static.

Below is a code snippet of a singleton in C#. We have defined the constructor as private, defined all the instances and methods using the static keyword as shown in Figure 14.5. The static keyword ensures that only one instance of the object is created and you can all the methods of the class without creating the object. As we have made the constructor private, we need to call the class directly.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 5

Question 7.
Can you explain the Facade pattern?
The facade pattern sits on the top of the group of subsystems and allows them to communicate in a unified manner (See Figure 14.6).

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 6

Figure 14.7 shows a practical implementation of the same. In order to place an order, we need to interact with product, payment, and invoice classes. So order becomes a facade that unites product, payment, and invoice classes.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 7

Figure 14.8 shows how class ‘clsOrder’ unifies / uses ‘ clsProduct’, ‘clsProduct’ and 1 clslnvoice’ to implement ‘PlaceOrder’ functionality.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 8

Question 8.
What is the difference between Dl and loC?
The main goal of Inversion of control and Dependency Injection (Dl) is to remove dependencies of an application. This makes the system more decoupled and maintainable.
First, let’s try to understand IOC (Inversion Of Control). If you go back to old computer programming days, program flow used to run in its own control. For instance, let’s consider a simple chat application flow as shown in the Figure 14.9 flow diagram.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 9

  1. End-user sends a chat message.
  2. The application waits for the message from the other end.
  3. If no message is found it goes to Step 2 or else moves to Step 4.
  4. Displays the message.
  5. The user continues with his/her work ahead.

Now if you analyze the program flow closely, it is sequential. The program is in control of itself, inversion of control means the program delegates control to someone else who will drive the flow. For instance, if we make the chat application event-based then the flow of the program will go something as below:

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 10

  1. End-user sends chat messages (See Figure 14.10).
  2. The user continues with his work ahead.
  3. The application listens to events. If a message arrives event is activated and the message is received and displayed.

If you see the program flow it is not sequential, it is event-based. So now the control is inverted. So rather than the internal program controlling the flow, events drive the program flow. The event flow approach is more flexible as their no direct invocation which leads to more flexibility

A word of caution here, do not conclude that loC are implemented by only events. You can delegate the control flow by callback delegates, observer pattern, events, Dl (Dependency Injection), and a lot of other ways.
loC (Inversion of Control) is a general parent term while Dl (Dependency Injection) is a subset of loC. C is a concept where the flow of the application is inverted. So for example rather than the caller calling the method.

SomeObj ect.Call( );

Will get replaced with an event-based approach as shown below.

SomeObject.WhenEvent += Call( );

In the above code, the caller is exposing an event, and when that event occurs he/she is taking action. It’s based on the Hollywood principle “Don’t call us we will call you”. In Hollywood when artists used to give auditions the judges would say to them “Don’t call us we will call you”.
The above approach makes code more flexible as the caller is not aware of the object methods and the object is not aware of caller program flow.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 11

Dl provides objects that an object needs. So rather than the dependencies construct themselves they are injected by some external means. For instance, let’s say we have the class “Customer” who uses a “Logger” class to log errors as shown in Figure 14.2. So rather than creating the “Logger” from within the class, you can inject the same via a constructor as shown in the below code snippet.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 12

The biggest benefit achieved by the above approach is “Decoupling”. You can now invoke the customer object and pass any kind of “Logger” object as shown in the below code.
Customer obj = new Customer(new EmailLogger());
Customer obj1 = new Customer(new EventViewerLogger());

Inversion of control Dependency injection
It is a generic term and implemented in several ways (events, delegates, etc.) Di is a subtype of loC and is implemented by constructor injection, setter injection, or method injection.

Question 9.
What are MVC, MVP, and MWM patterns?
All the above design patterns come in the presentation pattern category and help to remove any kind of cluttered code in Ul like manipulation of user interfaces and maintaining state. Thus keeping your Ul code cleaner and better to maintain.

Question 10.
What is the MVC pattern?
The main purpose of using the MVC (Model View Controller) pattern is to decouple the GUI (Graphics User Interface) from the Data. It also gives the ability to provide multiple views for the same Data. MVC pattern separates objects into three important sections:

• Model: This section is especially for maintaining data. It is actually where your business logic, querying database, database connection, etc., is actually implemented.

• Views: Displaying all or some portion of data, or a probably different view of data. The view is responsible for look and feel, sorting, formatting, etc.

• Controller: They are event-handling section, which affects either the model or the view. The controller responds to the mouse or keyboard input to command model and view to change. Controllers are associated with views. User interaction triggers the events to change the model, which in turn calls some methods of model to update its state to notify other registered views to refresh their display.

Question 11.
How can we implement MVC in ASP.NET?
By using theASP.NET template provided in Visual Studio.

Question 12.
What is MVP?
MVP (Model View Presenter) has the same goals as MVC, i.e., separating the III from the model. It does the same by using a presenter class. The Ul talks via an interface to the presenter class and the presenter class talks with the model.

The presenter class contains all the code needed for model communication and synchronization.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 13

Question 13.
What is MWM?
Again MWM is an architectural pattern with the focus of removing Ul cluttered code. It does the same by using an extra class called a view model. MWM is mostly suitable for Silverlight and WPF projects because of the rich bindings provided by the technologies.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 14

So Ul talks with the view model class and the view model class interact with the model class.

Question 14.
What is the difference between MVC, MVP, and MWM, and when to use what?
MVC: Here the first hit comes to the controller and the controller ties up the view and model and sends the same to the user.
MVP: Here the first hit comes to the Ul and the Ul interacts with a presenter class who talks with the model.
MWM (Model-View-View-Model): here the first hit comes to Ul and Ul talks to the model via a separate class called a view model. Rich bindings are used by the view model class to communicate to the model thus keeping the Ul code clean.
MVC is good for Web applications like ASP.NET, MVP for windows applications, and MWM for Silverlight and WPF projects as they have rich bindings.

Question 15.
What is three-tier architecture?
The three-tier software architecture emerged in the 1990s to overcome the limitations of the two-tier architecture.

Question 16.
There are three layers when we talk about three-tier architecture:
User Interface (Client): This is mostly the windows user interface or the Web interface but this has only the Ul part.

Mid-layer: Middle tier provides process management where business logic and rules are executed and can accommodate hundreds of users (as compared to only 100 users with the two-tier architecture) by providing functions such as queuing, application execution, and database staging.

Data Access Layer: This is also termed by the famous acronym “DAL” component. It has mainly the SQL statement which do the database operation part of the job.

Question 17.
Have you ever worked with Microsoft Application Blocks, if yes then which?
Application Blocks are C# and VB.NET classes distributed as Visual Studio projects that can be downloaded from Microsoft’s Website and used in any .NET application, including ASP.NET Web applications. They are useful and powerful tools that can make applications more maintainable, scalable, and efficient
Secondly, which application blocks have been used depends on really what you have implemented. However, there are two famous MABs, which is making buzz around the industry:
Data access block: Data access block gives us a readymade DAL component.
Exception management block: This block gives us reusable classes which can reduce exception handling in the project.

Question 18.
What is service-oriented architecture?
“Services” are components, which expose well-defined interfaces, and these interfaces communicate through XML messages. Using SOA (Service Oriented Architecture), you can build a workflow, which uses interfaces of these components. SOA is typically useful when you are crossing heterogeneous technical boundaries, organizations, domains, etc.
In .NET, SOA technically uses Web services to communicate with each service, which is crossing boundaries. You can look at SOA, which sits on top of Web services and provides a workflow.
SOA uses service components, which operate in their own domain boundary. Let us note some points of service:

  • They are independent components and operate in their own boundary and own technology.
  • They have well-defined interfaces, which use XML and WSDL (Web Services Description Language) to describe themselves.
  • Services have URLs where anyone can find them and clients can bind to these URLs to avail of the service.
  • Services have a very loosely coupled architecture. In order to communicate to service you only have to know the WSDL (Web Services Description Language). Your client can then generate a proxy from the WSDL of the service.

Figure 14.15 describes a broader picture of what service-oriented architecture will look like. The fundamental of SOA is a Web service. In the above diagram, you can see there are two services available. One is the “Credit Card” service and the other is the “Address Check” Web service.

Both these services are provided by a different company. Now we want to build functionality, which needs to validate a credit card and check that addresses are proper. In short, we will need functionalities of both the “Credit Card” and “Address Check” services. Also, note the “Credit Card” service has its own business layer and DAL components, which can be in a proprietary language.

It is very much possible that the whole Credit card service is made in .NET and the Address check is SAP (Systems, Application, and Products) implementation or Java implementation. However, because both the systems provide their functionality using Web services which is nothing but XML message communication. So we have made a new service that sits like a FAQADE on top of both the Web service and performs both functionalities in one common service. You will see I have made a third service which sits on top of both the Web service and consumes them. Also, you can see that the Ul part of the systems has access to the Business layer and Web service of their system. However, the service which does both these checks has only access to the Web service.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 15

Note: It’s beyond the scope of this book to discuss SOA. However, just to keep you safe during the interview this book has tried to clear some basics of SOA. I will really stress you to read the WCF chapter of this book, which talks in detail about how Microsoft has visualized SOA.

Question 19.
What are different ways you can pass data between tiers?
There are many ways you can pass data between tiers:

  • Dataset is the most preferred one as they maintain data in XML format.
  • Data reader
  • Custom classes.
  • XML

Question 20.
What is UML?
The Unified Modeling Language (UML) is a graphical language for visualizing, specifying, constructing, and documenting the artifacts of a software-intensive system. UML provides blueprints for business processes, System functions, programming language statements, database schemas, and reusable components.

Question 21.
How many types of diagrams are there in UML?
There are nine types of diagrams in UML:
Use case diagram: They describe the “WHAT” of a system rather than “HOW” the system does it. They are used to identify the primary elements and processes that form the system. The primary elements are termed as “actors” and the processes are called “use cases”. Use Case diagrams show “actors” and their “roles”.

Class diagram: From the use case diagram, we can now go to the detailed design of system, for which the primary step is class diagram. The best way to identify classes is to consider all “NOUNS” in use cases as classes, “VERBS” as methods of classes, relation between actors can then be used to define the relation between classes. The relationship or association between the classes can be either an “is-a” or “has-a” relationship which can easily be identified from use cases.

Object diagram: An object is an instance of a class. Object diagram captures the state of classes in the system and their relationships or associations at a specific point of time.

State diagram: A state diagram, as the name suggests, represents the different states that objects in the system undergo during their life cycle. Object change in response to certain simulation so this simulation effect is captured in state diagram. Therefore, it has an initial state and final state and events that happen in between them. Whenever you think that some simulations are complicated, you can go for this diagram.

Sequence diagram: Sequence diagrams can be used to explore the logic of a complex operation, function, or procedure. They are called sequence diagrams because sequential nature is shown via ordering of messages. First message starts at the top and the last message ends at bottom. The important aspect of a sequence diagram is that it is time-ordered. This means that the exact sequence of the interactions between the objects is represented step-by-step. Different objects in the sequence diagram interact with each other by passing “messages”.

Collaboration diagram: A collaboration diagram groups together the interactions between different objects to fulfil a common purpose.

Activity diagram: Activity diagram is typically used for business process modeling, for modeling the logic captured by a single use case, or for visualizing the detailed logic of a business rule. Complicated process flows in the system are captured in the activity diagram. Similar to a state diagram, an activity diagram also consists of activities, actions, transitions, initial and final states, and guard conditions. However, difference is state diagrams are in the context of simulation while activity gives a detailed view of business logic.

Deployment diagram: Deployment diagrams show the hardware for your system, the software that is installed on that hardware, and the middleware used to connect the disparate machines to one another. It shows how the hardware and software work together to run a system. In one, line its shows the deployment view of the system.

Component diagram: The component diagram represents the high-level parts that make up the system. From the .NET angle point of view, they form the “NAMESPACES”. This diagram depicts, at a high level, what components form part of the system, and how they are interrelated. Its shows the logical grouping of classes or group of other components.

Note: The best way to remember all the blocks of UML is “Serve cool SOUP during church ceremony” that covers 
State chart, Class diagrams, Sequence diagram, Object diagram, Use Case diagram, Package diagram, Deployment 
diagram, Collaboration diagram, Component diagram.

Question 22.
What are the advantages of using UML?
Modeling has been around for years, not only in software field but also in other trades like civil, mechanical etc. For example in civil engineering drawing the main architecture built of the diagram is a model by itself. Modeling makes complex and huge system to break up into simple and discrete pieces that can be individually understood. Example simple flowchart drawing is modeling.
There are two main advantages of modeling:

  • Readability: Representing your whole architecture in flowchart, class diagrams, ER (Entity Relationship) diagrams, etc., makes your project more readable. Especially when programmer’s change jobs handover becomes easier. More the project is not readable more the dependencies.
  • Reusability: After the system is more readable and broken down into pieces, it becomes easier to identify redundant and similar modules. Thus increasing reusability.

So why UML? Well, different languages have different ways of coding and syntaxes. In order to bring all languages in one roof UML is in to picture. As the term comes in Unified, it unifies all disparate languages in one roof so people who are working on some other platforms can understand that.

Question 23.
How did you implement UML in your project?
First, let me say, some fact about this question, you cannot implement all the nine diagrams given by UML in one project; you can but can be the very rare scenario. The way UML is implemented in project varies from project to project and company to company.
A second very important point to remember is normally all diagrams are not implemented in a project, but some basic diagrams are important to have in order for the project to be readable. When we talk about projects every project has phases example (Requirements phase, the design phase, the coding phase, etc.). As every phase of the software cycle proceeds, these diagrams come into the picture. Some diagrams span across multiple phases.

Note: If you want to have a detail about software life cycle look out for chapter “Project Management”.

Normally following are different basic phases:

Requirement phase (Use Case Diagrams, Activity diagrams)

The requirement phase is the phase where you normally gather requirements and use cases are the best things to make the explanation of the system. In requirement phase, you can further make complicated use cases more simple and easy to understand by using activity diagrams, but I do not see it as a must in every project. If the use cases are complicated, go for a Activity diagram. Example CRUD (Create, Read, Update and Delete) operation use cases have no significance for making activity diagrams. So in short, the outcome UML documents from requirement phase will be use case and Activity diagram documents (Activity diagram documents will only be there if there are complicated use cases to be simplified).

Note: This question is specially asked to know have you actually used UML. I have seen many guys trying to 
give some jack of all answers saying “YES”. Beware it is a trap.

Not all diagrams are needed in project example: Activity diagrams will only be needed when you want some simplified look of a complicated use case.

Design phase (Class diagrams, object diagrams, Component diagrams, Collaboration diagrams, Deployment diagrams, Sequence diagrams)

Design phase is the phase where you design your technical architecture of your project. Now again in this you do not use all UML documents of a project.

However, the next document after the use case document will be the Component diagram. Component diagrams form a high-level classification of the system. So after “Use Cases” just try to come out with a high-level classification / grouping of related functionalities. This should be compulsory diagram, as outcome of this document will form “NAMESPACES” structure of .NET project.

Ok now once your high-level grouping is done you can go ahead with class diagrams. Especially from Use Case you get the “NOUNS” and “VERBS” which can form the class name and the method name respectively. From my point of view, class diagrams should be compulsory in projects.

Object diagrams are not compulsory it depends on how complicated your project. Object diagrams show the relation between instances of class at runtime. In short, it captures the state and relation of classes at any given moment of time. Example you have class which creates objects of different classes, its like a factory. In class diagram, you will only show that it as a simple class with a method called as “Create Object”. However, in object diagrams actually you will show the types of instances create from that object.

Collaboration diagrams mainly depict interaction between object to depict some purpose. I find this diagram to be more useful than Object diagrams as they are addressed for some purpose example “Login Process” which will use “Login object”, “User Object”, etc., to fulfill the login purpose. Therefore, if you find the process very complicated go for this diagram. I see as a thumb rule if there is an activity diagram, which shows some serious complicated scenarios. I will like to go for this diagram in order to simplify the explanation.

State chart diagram is again created if your project requires it. If your project has some complicated start and end states to show then this diagram is most useful. Recently I was making a call center project where the agent phone pickup and hang state has to be depicted. So my first state was when agent picks up the phone and the final stage was when agent hangs the phone, in between process was very complicated, which can only be shown by using state chart diagrams.

Sequence diagrams are needed if some sequence is complicated. Do not confuse sequence diagrams with Activity diagram, Activity diagrams map to a use case while sequence diagrams show object interaction in sequence.

Deployment diagrams are again not a compulsory requirement. It will show the hardware and software deployment of your system. If you really have leisure in your project go for it or if you want to make the client smile seeing some diagrams.

Implementation phase / Coding phase (Class diagrams for reverse Engineering, other diagrams for validity check)

In this phase, mostly class diagrams are re-engineered with the source code. However, other diagrams are also present for validity check example state chart diagrams will be used in case to check that the both activity between those states follow the proper logic. If some things have to be changed, then again there is iteration backward to the Requirement phase.

Testing phase

This phase mostly goes for the testing department. I am not talking about preparing UTP (Unit Test Plans) but SITP (System Integration Test Plans). Where the testing department will look at all diagrams to prepare a test plan and execute it. For example it will see the use case document to see the business rules, it will see the activity diagram and sequence diagrams to see the proper flow of modules. If some things are not proper, there is iteration back to the Design phase.

Roll out and close over phases.

All documents just to re-check that things are proper, for example, all modules deployed according to the deployment diagrams, are all business rules in use cases satisfied.

Let us revise the following points:

  • Not all diagrams are compulsory.
  • The minimum diagrams according to software life cycle phases are:
  • Requirement phase: Use case diagrams o Design Phase: Component diagrams, class diagrams
  • Implementation phase: All diagrams derived from pervious phases specially class diagram for reverse engineering.
  • Testing phase: All diagrams derived from requirement and design phases for verification and preparing test plans.
  • Roll out and close over phase: All document derived from Design phase and requirement phases.

Figure 14.16 shows all the documents in relevant phases.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 16

Note: This book will now attempt to describe every element of a UML diagram. But it is advisable that you
 should install any decent UML tool and do a small practice of one or two diagrams which will make you comfortable 
during the interview.

Question 24.
What are the different phases in a software life cycle?
There are six phases in software development:

  • Requirement
  • Design
  • Coding and unit testing
  • System testing
  • Acceptance testing
  • Go live

Question 25.
Can you explain different software development life cycles?
SDLC (System Development Life Cycle) is the overall process of developing information systems through multi-stage process systems from the investigation of initial requirements through analysis, design, implementation, and maintenance. The days are gone when one COBOL (Common Business Oriented Language) programmer used to analyze, test, and implement software systems. Systems have become complex, huge team members are involved, architects, analysts, programmers, testers, users, etc. To manage this number of SDLC models have been created.
Following are popular models, which are listed:

  • Waterfall Model
  • Spiral Model
  • Build and Fix model
  • Rapid prototyping Model
  • Incremental Model

Let discuss each of the SDLC models in brief.

Water Fall Model

This is the oldest model. It has a sequence of stages; the output of one stage becomes the input of the other. Following are stages in the Waterfall model:

• System Requirement: This is the initial stage of the project where end-user requirements are gathered and documented.

• System Design: In this stage detailed requirements, screen layout, business rules, process diagram, pseudo code, and other documentation are prepared. This is the first step in the technical phase.

• Implementation: Depending on the design document, actual code is written here.

• Integration and Testing: All pieces are brought together and tested. Bugs are removed in this phase.

• Acceptance, Installation, and Deployment: This is the final stage where software is put in production and runs actual business.

• Maintenance: This is the least glamorous phase, which runs forever. Code Changes, correction, addition, etc., are done in this phase.

The waterfall is suited for low risk in areas of User Interface and performance requirements, but the high risk in budget and schedule predictability and control. Waterfall assumes that all requirements can be specified in advance. But unfortunately, requirement grows and changes through various stages, so it needs feedback from one stage to other.

Spiral Model

Spiral Model removes the drawback of the waterfall model, by providing emphasis to go back and reiterate earlier stages a number of times as the project progresses. On a broader level, it is a series of short waterfall cycles, each producing an early prototype representing a part of the entire project. It also helps demonstrate a Proof of Concept in the early software life cycle.

Build and Fix Model

This is the way free-lancers work write some code and keep modifying it until the customer is happy. This approach can be quite dangerous and risky.

Rapid Prototyping Model

This model is also called Rapid Application Development (RAD). The initial emphasis is on creating a prototype that looks and acts like the desired product. The prototype can be created by using tools, which are different from those used for the final product. Once the prototype is approved, it’s discarded and real software development is started from scratch. The problem with this model is that sometimes the prototype moves ahead to become the final live product, which can be bad from the design point of view. It is an effective model but can have higher costing than other models as you require programmers during the initial phase of the software cycle.

Incremental Model

In this model, we divide products into builds, where sections of products are created and tested separately. Here errors are found in the requirement phase itself, user feedback is taken for each stage, and code is tested after it is written.

Question 25.
What does Agile mean?
Dictionary meaning of Agile is quick moving. Now how does that apply to software? Agile development methodology considers software as the most important entity and accepts user requirement changes. Agile advocates that we should accept changes and deliver the same in small releases. Agile accepts change as a norm and encourages constant feedback from the end-user.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 17

The below figure shows how Agile differs in principles from traditional methodologies.

  • It’s not necessary to have hi-fi tools and processes but a good team interaction can solve a lot of problems.
  • Working software is more important than documentation.
  • Management should not pay attention to only customer contracts rather interact with customers and analyze the requirements.
  • \n trarMonat methodologies we pledge to stock. our plans but age says the customer wants to change, analyze and change your plan accordingly”.

Below are principles of Agile methodology:

  • Welcome change and adapt to changing requirements
  • Working software is the main measure of progress.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 18

  • Customer satisfaction is the most important thing and that can be attained by rapid, continuous delivery of useful software
  • Day-to-day meetings between business people and the development team is a must.
  • Businesses and developers must work together. Face to face to communication is the most important thing.
  • Deliver and update software regularly. In Agile we do not deliver software in one go, but rather we deliver frequently and deliver the important features first.
  • Build projects around teams of motivated and trustful people.
  • Design and execution should be kept simple.
  • Strive for technical excellence in design and execution.
  • Allow the team to organize themselves.

Question 26.
What is Scrum?
SCRUM is a methodology which believes rapid changes of customers cannot be solved by the traditional approach. So it adopts an empirical approach where it believes the problem can not be understood or defined. Rather concentrate on the team’s ability to respond to the emerging requirements.

Question 27.
What do product owner, product backlog, and sprint mean in Scrum?
Before we understand the SCRUM cycle let’s get familiar with some terms regarding SCRUM.

The Product Owner is the end customer or the user.
A product backlog is a list of prioritized items to be developed for a software project.
Sprint is the task breakup of a product catalog. It’s the detailed task breakdown for a development team.

Figure 14.19 shows a typical product catalog broken into sprints. On the left-hand side of Figure 14.19, we have shown two items in the product backlog “Create Customer” and “Create Supplier”. To complete “Create Customer” the developer need to the following sprint task “Code Business Logic”, “Design Ul” and “Prepare Test Plans”.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 19

Question 28.
Can you explain how Scrum flows?
Figure 14.20 shows how the development flow moves in a project. We will understand the SCRUM flow step-by-step.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 20

Step 1: The product owner (i.e., the customer) creates a list of product logs (list of functionalities).
Steps 2 and 3: In these phases, we sit with the customer and prioritize the product catalog. We discuss with the customer which functionality is a must and must be delivered first.
Steps 4 and 5: In both these phases we break down the product catalog into tasks called sprint backlog.
Step 6: We start executing the sprint task and monitoring the sprint activity.
Steps 7 and 8: Once we are done with the sprint activity, we take the next sprint/task by again going to the sprint phase.
Step 9: If there are no more sprints/tasks the product log is completed, which means the project is completed.

Question 29.
Can you explain the different roles in SCRUM?
Scrum has some different terminologies when it comes to role names in Scrum (See Figure 14.21). Below is the list of roles with what actually they mean.
People with pig roles are those people who are committed to the project. If the project fails it affects these people. So of the big roles are developer, customer, project manager, etc.

Product owner means the end customer or user.

Scrum master is the process driver. These are the people who drive the scrum process. They are consultants for the Scrum process.
People with chicken roles work indirectly on the project. They do not really benefit from the project but their feedback is valuable to the project. They cannot be held responsible if the project is not successful.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 21

Question 30.
When should we choose Agile and when should we choose waterfall?
Agile is the best choice when your requirements are evolving and not fixed. If your requirements are fixed waterfall becomes a better choice.

Question 31.
What are some of the important metrics in the project?
There are different kinds of metrics but there are three prime metrics planned value, earned value, and actual cost. These three metrics help us to understand where the project stands today.

Question 32.
What is effort variance?
Effort Variance = (Actual effort – Estimated Effort) / Estimated Effort.

Question 33.
What is CAR (Causal Analysis and Resolution)?
The basic purpose of CAR is to analyze all defects, problems, and good practices/positive triggers in projects, perform a root cause analysis of the same, identify respective corrective and preventive actions, and track these to closure. The advantage of CAR is that root causes are scientifically identified and
their corrective and preventive actions are carried out. CAR needs to be performed at project initiation, all phases and project ends, and on a monthly basis. A Fishbone diagram is one of the ways you can do CAR.

Question 34.
What is DAR (Decision Analysis and Resolution)?
Decision Analysis and Resolution is to analyze possible decisions using a formal evaluation process that identifies alternatives against established criteria.
For example, in a project, you are said to use third-party tools so you will not depend on only one tool but evaluate three to four more tools so that in case of problems you have alternatives. This is called as DAR.

Question 35.
What is a fishbone diagram?
Dr. Kaoru Ishikawa invented the fishbone diagram. Therefore, it can be also referred to as the Ishikawa diagram.A Fishbone diagram is an analysis diagram, which provides a systematic way of looking at effects and the causes that create or contribute to those effects. Because of the function of the fishbone diagram, it may be referred to as a cause-and-effect diagram. The design of the diagram looks much like the skeleton of a fish. Therefore, it is often referred to as the fishbone diagram.

Fishbone diagram helps in categorizing potential causes of problems or issues in an orderly way and in identifying root causes.
Figure 14.22 shows a sample of fishbone diagram, which illustrates why a project deadline was not met. The middle arrow is the main problem “Deadline not met”. Then we start analyzing other problems, which have led to this problem. For example, there is client problem — as he/she is always changing the requirement — this is caused because the company did not sign the SRS (Software Requirements Specification) — and this happened as proper project management procedures where not at place. So to solve this problem we either appoint a project manager or give training on project management to senior team members.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 22

Question 36.
What is Pareto principle?
Pareto principle also paraphrased as 80/20 principle is simple effective problem tackling way in management. It says that 20% of your problems lead to other 80 % of problems. So rather than concentrating on the 80% of problem if you concentrate on 20% of problems you can save lot of trouble. So in pareto you analyze the problems and only concentrate on 20% of your vital problems. In projects, the first 10% and the last 10% of project form the vital part of project.

Question 37.
What are functional and non-functional requirements?
Functional requirements defines “What” of the system while non-functional requirement define “How” of the system. Function requirements define business requirements while non-functional requirement define technical requirements.

Below is a simple example in both of them:
Functional: Display the report how much sales have been done this month.
Non-functional: The report should be displayed in 15 seconds.

Question 38.
How do you handle change request?
Normally change requests are handled by preparing an Impact analysis document and then doing re¬estimation. Example you have an ongoing project, which has a customer table. Now customer wants to also have addresses assigned to it. Therefore, you normally raise a change request and then do an impact analysis of the same. Depending on the impact, you estimate and let know the client about the financial aspect of the project. Once client sign off or the upper management agrees to the change request you move ahead with implementation.

Question 39.
What is internal change request?
Internal change request are not normally billable change request, it has no financial gains from the client. Example your architecture division of your company has said in mid of the project that the architecture has to be modified. Definitely this has nothing to do with the client, but you make changes to the project so this is called as Internal change request.

Question 40.
What is difference between SITP and UTP in testing?
UTP (Unit Test Plan) are done at smallest unit level or stand-alone mode. Example you have Customer and invoicing module. So you will do test on Customer and invoice module independently. But later when we want test both customer and invoice in one set we integrate them and test it. So that’s is SITP (System Integration Test Plan)
UTP can be done using NUnit (an open source unit testing framework for Microsoft .NET). Unit testing is done normally by developers and System testing is done normally by testing department in integration mode.

Question 41.
Which software have you used for project management?
Many companies have there own software defined. There are many project management software available at this moment in market but this can vary from company to company.
Worst it can vary from project to project. But Microsoft project is the most used software at this moment. So just brush your skills on Microsoft project, its used heavily across industry.

Question 42.
People in your project do not perform, what will you do?
In such kind of question, they want to see your delegation skills. The best answer to this question is a job of a project manager is managing projects and not problems of people, so I will delegate this work to HR (Human Resource) or upper authority…. Thanks to my Project Manager for this beautiful answer.

Question 43.
What is black box testing and White box testing?
Black box testing is also termed as functional testing. It ignores how the internal functionality of a system works and depends only what are the outputs on specified inputs. Source code availability is not an important in back box testing. Black box testing is mostly to ensure that it meets the user functionality.
According to IEEE (Institute of Electrical and Electronics Engineers), standards following are characteristics of Black box testing:

  • “Testing that ignores the internal mechanism of a system or component and focuses solely on the outputs generated in response to selected inputs and execution conditions,”
  • “Testing conducted to evaluate the compliance of a system or component with specified functional requirements.”

One of the way of doing black box testing is Manual testing what the tester performs. For instance, you can install the application on a machine and tester starts testing is a type of black box testing. In our case the tester is completely unaware of the how the program logic flows and how its coded, etc.

White box testing is opposite to Black box it requires internal know how of how the logic flows. As this testing needs know how of the internal structure it can only be done programmers. Unit testing is one of the ways of doing White box testing in which programmers use NUNIT or JUnit (a unit testing framework) to test each class individually. White box testing can be done by programmer by either stepping through the code or testing the classes and components in isolation.

Question 44.
What is the difference between Unit testing, Assembly testing and Regression testing?
Unit testing is also termed as Component testing. This testing ensures that reliable program unit meets their requirements. Unit testing is normally conducted by programmer under the supervision of the project lead or the team Lead. Main objective of this testing is to test each unit in isolation and individually. This is done by knowing what the inputs to the unit are and what the expected outputs for the same. Unit testing is a white box activity. Unit test normally comes in the implementation phase of the project.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 23

For instance in Figure 14.23, we are trying to do unit testing on the customer class. So we create the object of the Customer class assign “CustomerCode” and “Age” properties and check for the response. For instance, in this condition, we tried to pass a non-numeric value to the “Age” property and the class threw an error saying, “Age should be numeric”. So here the basic unit testing entity is your class.

However, unit testing is not limited to a component, object, or function. Therefore, the definition of unit testing will depend on the approach. Below are some examples of unit testing:

  • Checkpoints in Ul (User Interface) like tab orders, error messages, look and feel, etc.
  • Class, object, component-level testing as said previously. In the case of functional programming can be a simple method or function.
  • Logic testing for algorithms. Some projects can have some critical algorithm for instance some kind of custom sorting, security implementation, etc. Therefore, that logic can be tested independently.

However, the general thumb rule of what is Unit in Unit testing is that the module is self-contained and by itself.

Assembly testing goes one step ahead of unit testing. It demonstrates that can the modules interact in a correct, stable, and proper manner as defined by the functional specifications provided by the client. Assembly testing is a Black box testing style and is also called Integration testing. For instance, in the above unit test of the “Customer” class, testing was done in isolation. But in actuality the “Customer” class is not going to be stand alone rather it will be used more in conjunction with the “Product” class and also will have Ul do the same. So in short, the “Customer” class will work with two more entities one is the “Ui” and the other is the “Product” class (See Figure 14.24). So normally, assembly testing is done through Ul but not necessarily.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 24

Figure 14.24 defines a simple scenario for integration testing. The same “Customer” class is now tested with the “Ul” and “Product” to see if the interaction between them matches according to functional specifications.

Regression testing ensures that applications function properly even if there are changes or enhancements to the system. For instance, you change the “Product” class still will run all the test cases for “Product”, “Customer” and “Ul” just to make sure that any changes in the “Product” class do not affect interaction with other entities. So you will see when testers do regression testing they run all the scripts to ensure that nothing has been affected.

Question 45.
What is V model in testing?
V model maps the type of test to the stage of development in a project (See Figure 14.25). V model stressed the point that every phase in project should have a test phase also.
Unit Testing: Starting from the bottom the first test level is “Unit Testing”. It involves checking that each feature specified in the “Component Design” has been implemented in the component.
In theory, an independent tester should do this, but in practice, the developer usually does it, as they are the only people who understand how a component works. The problem with a component is that it performs only a small part of the functionality of a system, and it relies on co-operating with other parts of the system, which may not have been built yet. To overcome this, the developer either builds, or uses special software to trick the component into believe it is working in a fully functional system. This test maps with the implementation phase and normally developers do the unit testing for the project.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 25

Integration Testing: As the components are constructed and tested they are then linked together to check if they work with each other. It is a fact that two components that have passed all their tests independently when connected to each other produce one new component full of faults. These tests can be done by specialists, or by the developers.

Integration Testing is not focused on what the components are doing but on how they communicate with each other, as specified in the “System Design”. The “System Design” defines relationships between components.

The tests are organized to check all the interfaces until all the components have been built and interfaced with each other producing the whole system. Integration test cases are written when design documents are written.

System Testing: Once the entire system has been built then it has to be tested against the “System Specification” to check if it delivers the features required. It is still developer-focused, although specialist developers known as systems testers are normally employed to do it.

In essence, system testing is not about checking the individual parts of the design, but about checking the system as a whole. In fact, it is one giant component.

System testing can involve a number of specialist types of tests to see if all the functional and non¬functional requirements have been met. In addition to functional requirements, these may include the following types of testing for the non-functional requirements:

  • Performance – Are the performance criteria met?
  • Volume – Can large volumes of information be handled?
  • Stress – Can peak volumes of information be handled?
  • Documentation – Is the documentation usable for the system?
  • Robustness – Does the system remain stable under adverse circumstances?

There are many others, the need for which is dictated by how the system is supposed to perform. System test plans are written when the specification of the project is going on.

Acceptance Testing

Acceptance Testing checks the system against the “Requirements”. It is similar to systems testing in that the whole system is checked but the important difference is the change in focus:
Systems testing checks that the system that was specified has been delivered. Acceptance Testing checks that the system will deliver what was requested.

The customer should always do acceptance testing and not the developer. The customer knows what is required from the system to achieve value in the business and is the only person qualified to make that judgment. This testing is more of getting the answer for whether is the software delivered as defined by the customer. It is like getting a green flag from the customer that the software is up to the expectation and ready to be used. Acceptance test plans are written during the requirement phase of the project. In a real scenario, these test plans should be given by the end customer.

Question 46.
How do you start a project?
Left to the readers.

Question 47.
How did you do resource allocations?
Left to the readers.

Question 48.
How will you do code reviews?
The way in which code reviews are done changes from person to person and also company to company.
However, normally when a project is started project people define their architecture, coding standards, etc., in their design document. So before starting the code review you will have to go through the standards defined in the project. Reviews are done by two methodologies one is peer review and the other is by the external party who is not a member of the project. So we give the standard document to the reviewer he checks it, gives his perspective, and logs a review to the development. If the review is critical then the development team can close it or they can wave it off.

Question 49.
What is CMMI?
It is a collection of instructions an organization can follow with the purpose to gain better control over its software development process (See Figure 14.26).

Question 50.
What are the five levels in CMMI?
According to the SEI (Software Engineering Institute), there are five levels of the CMMI (Capability Maturity Model Integration).

Level 1 – Initial

At maturity Level 1, processes are usually ad hoc and the organization usually does not provide a stable environment. Success in these organizations depends on the competence and heroics of people in the organization and not on the use of proven processes. In spite of this ad hoc, chaotic environment, maturity Level 1 organizations often produce products and services that work; however, they frequently exceed the budget and schedule of their projects.
Maturity Level 1 organizations are characterized by a tendency to over-commit, abandon processes in the time of crisis, and not be able to repeat their past successes again.

Level 2-Repeatable

At maturity Level 2, software development successes are repeatable. The organization may use some basic project management to track costs and schedules.

Process discipline helps to ensure that existing practices are retained during times of stress. When these practices are in place, projects are performed and managed according to their documented plans.

Project status and the delivery of services are visible to management at defined points (for example, at major milestones and at the completion of major tasks).

Basic project management processes are established to track cost, schedule, and functionality. The necessary process discipline is in place to repeat earlier successes on projects with similar applications.

Level 3 – Defined

At maturity Level 3, processes are well characterized and understood and are described in standards, procedures, tools, and methods.
The organization has a set of standard processes, which is the basis for Level 3, which is established and improved over time. These standard processes are used to establish consistency across the organization. Projects establish their defined processes by the organization’s set of standard processes according to tailoring guidelines.

The organization’s management establishes process objectives based on the organization’s set of standard processes and ensures that these objectives are appropriately addressed.

A critical distinction between Level 2 and Level 3 is the scope of standards, process descriptions, and procedures. At Level 2, the standards, process descriptions, and procedures may be quite different in each specific instance of the process (for example, on a particular project). At Level 3, the standards, process descriptions, and procedures for a project are tailored from the organization’s set of standard processes to suit a particular project or organizational unit.

Level 4 – Managed

Using precise measurements, management can effectively control the software development effort. In particular, management can identify ways to adjust and adapt the process to particular projects without measurable losses of quality or deviations from specifications.

Subprocesses are selected that significantly contribute to overall process performance. These selected sub-processes are controlled using statistical and other quantitative techniques.

A critical distinction between maturity Level 3 and maturity Level 4 is the predictability of process performance. At maturity Level 4, the performance of processes is controlled using statistical and other quantitative techniques and is quantitatively predictable. At maturity Level 3, processes are only qualitatively predictable.

Level 5 – Optimizing

Maturity Level 5 focuses on persistently improving process performance through both incremental and innovative technological improvements. Quantitative process-improvement objectives for the organization are established, continually revised to reflect changing business objectives, and used as criteria in managing process improvement. The effects of deployed process

improvements are measured and evaluated against the quantitative process-improvement objectives. Both the defined processes and the organization’s set of standard processes are targets of measurable improvement activities.
Process improvements to address common causes of process variation and measurably improve the organization’s processes are identified, evaluated, and deployed.

Optimizing processes that are nimble, adaptable, and innovative depends on the participation of an empowered workforce aligned with the business values and objectives of the organization. The organization’s ability to rapidly respond to changes and opportunities is enhanced by finding ways to accelerate and share learning.

A critical distinction between maturity Level 4 and maturity Level 5 is the type of process variation addressed. At maturity Level 4, processes are concerned with addressing special causes of process variation and providing statistical predictability of the results. Though processes may produce predictable results, the results may be insufficient to achieve the established objectives.

At maturity Level 5, processes are concerned with addressing common causes of process variation and changing the process (that is, shifting the mean of the process performance) to improve process performance (while maintaining statistical probability) to achieve the established quantitative process-improvement objectives.

Note: I am sure during interview specially the SQA (Software Quality Assurance) guys expect all the different 
levels of CM Ml to be in mind. So below is the Figure 14.26, which will help you remembering the same.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 26

Question 51.
What is SIX Sigma?
Sigma means deviation in the Greek language. Deviation means how many variations exist in a set of data (See Figure 14.27). For instance, let’s say in a software maintenance project out of 100 defects 68 defects are rectified to the mark and the remaining bounce back means your bug fixing process is on “2 Sigma” level. I had described only from a bug fixing perspective. But this can be applied to any process organization.

UML, Estimation and Project Management Interview Questions in .NET chapter 14 img 27

Therefore, I should only have 3.4 defects in a million defects then I can say I am six sigma.

Question 52.
What are DMAIC and DMADV?
Six Sigma has two key methodologies DMAIC (Define, Measure, Analyze, Improve and Control) and DMADV (Define, Measure, Analyze, Design, Verify). DMAIC is used to improve an existing business process. DMADV is used to create new product designs or process designs in such a way that it results in a more predictable, mature, and defect-free performance.

Basic methodology consists of the following five phases:

  • Define: formally define the process improvement goals that are consistent with customer demands and enterprise strategy.
  • Measure: to define baseline measurements on the current process for future comparison. Map and measure the process in question and collect required process data.
  • Analyze: to verify the relationship and causality of factors. What is the relationship? Are there other factors that have not been considered?
  • Improve: to optimize the process based upon the analysis using techniques like the Design of experiments.
  • Control: set up pilot runs to establish process capability, transition to production, and thereafter continuously measure the process and institute control mechanisms to ensure that variances are corrected before they result in defects.

Basic methodology consists of the following five phases:

  • Define: formally define the goals of the design activity that are consistent with customer demands and enterprise strategy.
  • Measures: to identify CTQs (Critical to Quality), product capabilities, production process capability, risk assessment, etc.
  • Analyze: to develops and design alternatives, create a high-level design, and evaluates design capability to select the best design.
  • Design: to develop the detailed design, optimize design, and plan for design verification this phase may require simulations.
  • Verify: to design, set up pilot runs, implement the production process, and hand over to process owners. This phase may also require simulations.

Question 53.
What are the various ways of doing software estimation?
There are many techniques available for estimating a project:

  • Function points
  • Use Case points
  • WBS, etc.

Question 54.
What is function point estimation?
In function point, we break the application into smaller pieces called as elementary process and estimate the application.

Question 55.
How did you estimate by using function points?
Below are the steps in function points:

First Count ILF (Internal Logical File), EIF (External Interface File), El (External Input), EQ (External Inquiry), RET (Record Element Types), DET (Data Element Type), FTR (File Type Referenced) and use the rating tables. After you have counted all the elements, you will get the unadjusted function points.

Put rating values 0 to 5 to all 14 GSC (General System Characteristic). Adding all total 14 GSC to come out with total VAF (Value Adjustment Factor). Formula for VAF = 0.65 + (sum of all GSC factor/100).

Finally, make the calculation of the adjusted function point. Formula: Total function point = VAF * Unadjusted function point.

Make an estimation of how many function points you will do per day. This is also called as “Performance factor”.

On basis of performance factors, you can calculate Man/Days.

Question 56.
What is the FP per day in your current company?
Left to the readers as every company has its own FP (Function Point) per Day. For .NET its 0.8 FP
per day as a general standard.

Note: There is a free PDF (Portable Document Format) provided “How to prepare Software Quotations?” 
Please do refer Function point chapter.

Question 57.
What is SMC (System Management Controller) approach of estimation?
In this approach, we divide the project into small sections and assign complexity factories (simple, medium, and complex) to each of those sections. Each of these complexities is assigned man-days and the total man-days are estimated.

Question 58.
How do you estimate maintenance projects and change requests?
Most people use Simple, medium, and complex approaches for change request estimation.


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

Note: We can not visualize a project with out reports and yes we can not visualize a .NET interview which 
does not have a reporting question. So here we have a complete Chapter which will cover two basic reporting 
tools one is crystal and the other is reporting services.

Question 1.
How do we access crystal reports in .NET?
Crystal reports come with the Visual Studio setup itself. Right-click the Solution Explorer -> Add New Item and you can see a Crystal Report template as shown in Figure 16.1. You can add a ‘.rpt’ file using this template.

Reports Interview Questions in .NET chapter 16 img 1

Question 2.
What are the various components in crystal reports?
There are four major components in crystal reports Report designer, Reports engine, Report viewer, and object models.
Report designer gives a graphical interface to create and modify reports. To view the designer add a new crystal report file and double click on it you should see the report designer as shown in Figure 16.2.

Reports Interview Questions in .NET chapter 16 img 2

The reports engine does the formatting and conversion part of crystal reports. It helps convert the contents of reports in Word, Excel, PDF (Portable Document Format), HTML (HyperText Markup Language), and other formats. Report viewers are controls that you can see on the Visual Studio toolbox; you can drag and drop those controls on an ASPX page or windows application to view reports made using crystal. Object models help us manage crystal reports objects during design time and runtime.

Reports Interview Questions in .NET chapter 16 img 3

Question 3.
What basic steps are needed to display a simple report in crystal?
To understand this sample let display a simple report using crystal.
Step1: Create a Web application project.
Step2: Add New Item and select Crystal Report from the template. This adds a new rpt file in your Solution Explorer.
Step3: Double click on the rpt file click on Crystal Reports -> Field Explorer as shown in Figure 16.3. You

Reports Interview Questions in .NET chapter 16 img 4

Step 4 -> Right click on ‘Database Fields’ on the Field Explorer -> then click on Database Expert -> Expand Create New Connection -> Expand OLE DB ADO (Object Linking and Embedding, Database, Active Data Objects) -> Select Microsoft OLE DB provider for SQL (Structured Query Language) Server (this depends on what kind of data you want to connect) -> Give the Server Credentials a Click Finish and Done.

Step5: Right-click on ‘Database Fields’ on the Field Explorer -> then click on Database Expert -> Expand the Server, database and select table which you want to add to the report. Figure 16.4 shows the right pane showing the table added using Database Expert.

Step 6 -> Expand Database fields -> select Table (in this case it is ‘FactCurrencyRate’ Table). Now you can drag and drop the fields on the report as shown in Figure 16.5.

Reports Interview Questions in .NET chapter 16 img 5

Step 7 -> We now need to display the report on the ASPX page. For that, we need the ‘CrystalReportViewer’ control (See Figure 16.6). To expand the crystal reports section of the toolbar and drag the component on the ASPX page.

Reports Interview Questions in .NET chapter 16 img 6

Step 8: Now we need to go to code behind and specify the report source. That’s it now compile and run the project you can see your report live in action (See Figure 16.7).

Reports Interview Questions in .NET chapter 16 img 7

Question 4.
Can crystal reports be published as a Web service?
Right-click on the ‘rpt’ file and click ‘Publish as Web service’ as shown in Figure 16.8.

Reports Interview Questions in .NET chapter 16 img 8

Question 5.
How do we invoke the crystal report Web service?
We can consume the Web service as a normal Web service in . NET. The easiest way is by using the ‘ReportViewerControl’ and specifying the ASMX URL (Uniform Resource Locator) in the report source property.

Question 6.
How do we add formulas using crystal reports?
To add any formula in the crystal report is a three-step procedure. Figure 16.9 shows the three steps in a pictorial format.
Step 1 -> Go to Field Explorer and right-click and click the ‘Formula Fields’. Click ‘New…” option.
Step 2 -> The ‘Formula Name’ dialog box appears. Give and name to the formula in the ‘Name’ textbox and click on ‘Use Editor’.
Step 3 -> You will be presented with Ul which has all the formulas and functions.

Reports Interview Questions in .NET chapter 16 img 9

Question 7.
How do we pass parameters to crystal reports?
Sometimes we want to accept input parameters and the report works according to the parameter. To add an input parameter go to Field Explorer, go to Parameter Fields, right-click Create Parameter and you should be popped with a ‘Create Parameter Field’ dialog box as shown in Figure 16.9. Give a name to the parameter value, type and that’s it you are in action.

Reports Interview Questions in .NET chapter 16 img 10

Question 8.
How do we export from crystal reports?
There is two way of using the Export Options: one is when we display a report using Crystal Report Viewer you can see an export icon as shown in Figure 16.11 below. You can select the options given in the ‘Format:’ drop-down list in which format you want to export.

Reports Interview Questions in .NET chapter 16 img 11

The second option is through coding. Below is a sample code snippet that shows how we can export a report. Create an object of the crystal report and call the ‘ExportToDisk’ method specifying in which format you want to export.

Dim Report as New CrystalReportlReport.
ExportToDisk (CrystalDecisions.Shared.ExportFormatType. WordForWindows, "c: \my.doc")

Question 9.
How do we print to the printer using crystal?
In print we have two ways by which we can print one is when you display the report using Crystal Report Viewer you have a Print option and the second is by code. Below is a sample code snippet that shows how we have created an object called a report from the rpt file, specified the printer name, paper size, and then called the ‘ PrintToPrinter’ method.

Report.PrintOptions.PrinterName = "MyPrinter"
Report.PrintOptions.PaperSize = CrystalDecisions.Shared.PaperSize.PaperA4 Report.PrintOptions.PaperOrientation =
CrystalDecisions.Shared.PaperOrientation.Landscape Report.PrintToPrinter(1, True, 1, 3)

Question 10.
How do we generate cross-tab reports?
When we go for creating a new report you can see the cross-tab option in the ‘Choose, an Expert Section.

Reports Interview Questions in .NET chapter 16 img 12

Question 11.
How can we do grouping in crystal?
For grouping in crystal, you need to use the Group Expert Wizard.

Question 12.
Can you explain three-pass reporting which crystal report uses?

Reports Interview Questions in .NET chapter 16 img 13

Crystal report uses the three-pass method for parsing reports. Before we understand what does it means let’s define what is a pass? Pass is a process used by crystal reports to read and manipulate data as per the report format. Figure 16.13 shows how the parsing happens. Let’s understand the same step-by-step. In Pre-Pass1 crystal report engine evaluates constants like x = 1 and pie = 3.14 for a report. Pass 1 does two important things get data from the database and sort records with given conditions. Once this is done it’s saved in memory and given to pre-pass2 for further parsing and manipulation. Pre-pass2 is all about grouping and sorting the records according to conditions specified in the crystal report. Pass 2 formats a report, applies conditions,s and groups them. Pass 3 is the final tunnel it just counts the pages and generates reports.

Question 13.
Can you explain reporting services architecture?
Reporting services are mainly used to generate reports. Below are the main components of reporting services as shown in Figure 16.14. Reporting services have four major components Client, Web services, report server/manager, and reporting services database. Let’s understand all the major components and the sub-components of the same.

Client: These are the consumers of reporting services functionality. It can be the report manager or report server (we will discuss report server and manager in more detail further) or ASPX and Windows application.

Reports Interview Questions in .NET chapter 16 img 14

Reporting Web service: Microsoft chose XML to expose the functionality of reporting services. So all the functionality is exposed through Web services. One of the most important gains for a Web service is that it can be platform-independent.

Report server/manager: Report server and manager form the core engine of reporting services. There are two important systems one is a ‘Report processor’ and the other is a ‘Scheduling and Delivery Processor’. Reporting processor is the main driver to deliver reports. They take request from the end-user and process the report and send it to the end client. Figure 16.15 shows how the flow moves. We have seven basic steps which can help us understand in more detail how the report processor works.

Step 1 -> Any client like ASPX or Windows application will request to the Web service for reports.
Step 2 and 3 -> Web service will forward the request to the report processor and get the report definition from the report server DB.
Step 4 -> Reporting services uses the security extensions to authenticate the end-user.
Step 5 -> Data processing extension calls queries the application database to get data. With data processing extension we can connect to standard data sources like SQL Server, ODBC (Open Database Connectivity), Oracle, etc. You can also extend the data processing extension to adapt it to some custom data processing extensions.
Step 6 -> Rendering extension then renders the report applies format and sends the same to the end client. Using rendering extension you can deliver reports in Excel, PDF, HTML, CSV (Comma Separated Values), and XML. You can also extend the rendering extension to deliver in custom formats.

Reports Interview Questions in .NET chapter 16 img 15

The second system is ‘Scheduling and Delivery Processor. Delivery extensions make reports with the specified format and send the same to an output target like file, e-mail, FTP (File Transfer Protocol), etc. Scheduling and delivery processor does two important steps schedules reports and delivers them the same to an output like FTP,
Email etc. Schedule and delivery processor using the delivery extension to deliver reports to the defined output. So users can subscribe to the reports and depending on these subscriptions the delivery is done by schedule and delivery processor. There are two steps in this one is the subscription process and the other is the delivery process. Let’s first try to understand the subscription process. There are three steps basically as illustrated in Figure 16.16.

Reports Interview Questions in .NET chapter 16 img 16

Step 1 -> First is the request for a subscription to the report.
Step 2 -> This subscription is then stored in the report server DB.
Step 3 -> A new SQL Server agent is created for this subscription. So we have completed the subscription process.
Now that the subscription is created let’s see how the delivery process works. Here are five basic steps in the delivery process as shown in Figure 16.17.

Reports Interview Questions in .NET chapter 16 img 17

Step 1 -> When the event occurs SQL Server agent makes an entry in the report server DB.
Steps 2 and 3 -> RS windows service keeps polling SQL Server for any events. If an event has occurred it gets the event from the database and sends a message to the ‘Scheduling and Delivery Processor.
Step 4 -> The report is then processed by the report processor and sent to the delivery extension.
Step 5 -> who finally delivers it on an output which can be an e-mail address, folder, FTP, or any other kind of output.


Reporting Services Database: When you install reporting services you will see two databases ‘ReportServer’ and ‘ReportServerTempDB’ as shown in Figure 16.18. ‘ReportServer’ database contains report definitions, schedules, subscriptions, security details, and snapshots. ‘ReportServerTempDB’ store’s temporary information like session state about reports which is needed in-between HTTP requests and report cache information. Please note snapshots are stored in the report server and not in tempDB.

Reports Interview Questions in .NET chapter 16 img 18

Question 14.
We have two IIS applications ‘Reports’ and ‘Reportserver’ what do they do?
When you install reporting services there are two virtual directories created as shown in Figure 16.19.

Reports Interview Questions in .NET chapter 16 img 19

The ‘Reports’ virtual directory is like an admin. If you browse to HTTP: //your name/reports/home.aspx page you can view, edit properties, and display reports. We have Figure 16.20.
1 ->We can browse reports and see the output of reports.
2 -> We can upload an RDL (Report Definition Language) file directly in the report’s database.
3 -> Using the Report Builder link we build new reports.
4 -> Using the properties we can do role assignments.
5 -> Using the subscription link we can add new outputs (FTP, Folder, etc.,) to subscribe to the reports.
6 -> Site settings help us to decide how many numbers of snapshots we want in the history, report time out the execution, report execution logging, scheduling, manage jobs, and security settings.

Reports Interview Questions in .NET chapter 16 img 20

The second virtual directory is the ‘ReportServer’ this helps us to use browse reports and use the same in ASP.NET code using URL methodology, try browsing to HTTP: //vourpcname/report server/ you can easily figure out what this virtual directory is all about.

Question 15.
Can you explain Report Definition Language (RDL) file in reporting services?
RDL is an XML description of a report in reporting services. So basically the RDL file has the XML grammar which describes a reporting services report. Figure 16.21 shows a simple snippet of an RDL file.

Reports Interview Questions in .NET chapter 16 img 21

Question 16.
What is the basic process of making a report in reporting services?
Here are the basic steps which will help you in creating reports in reporting services:

  • Open Visual Studio 2005 -> File -> New Project -> Select ‘Business Intelligence Reports’ -> Select Report Server project.
  • When the project is created in the Solution Explorer you will see two folders ‘Shared Data resources’ (we will come to data sources in the coming questions) and ‘Reports’. Right-click the ‘Reports’ folder and click add new reports.
  • You need to give credentials in the Wizard. Once done it pops up a query builder. Specify the report query in the query builder and go next.
  • Wizard then helps you to select the report type and some other features. Next, you should see an RDL file in your ‘Reports’ folder.
  • Click on the View menu and select toolbox and you should be able to design the report.
  • Till now we are only in the design mode of report. As said previously all reports meta-data are stored in SQL Server database ‘ReportServer’. In order that the report’s meta-data to get saved in the database, we need to publish the report.
  • To publish the report we need to specify the IIS report path. So right-click on the report project, select properties, and specify the ‘TargetServerURL’ property.

Reports Interview Questions in .NET chapter 16 img 22

  • Once we have specified the ‘ TargetserverURL’ property we need to deploy the project. So right-click on the project and click ‘Deploy’.
  • You can now view your report using HTTP: //localhost/Reports/Pages/Folder.aspx URL.

Question 17.
How can we consume reports in ASP.NET?
There are three famous ways of calling reporting services report in ASP.NET:

  • Using URL way to access reports.
  • Using reporting Web service to programmatically access reports.
  • Using Report Viewer control,

URL way
This is the most basic way of accessing reports. We specify the URL as shown below which then displays the report on the browser. Figure 16.24 shows a basic format of how to display a report using the URL methodology.
1 -> This is the IIS (Internet Information Services) report application.
2 -> This is the project name or the project folder in which the report resides.
3 -> This is the report name.
4 -> This is the command to the reporting service of what to do. In this case we are saying render the report.

Reports Interview Questions in .NET chapter 16 img 23

If we want to get the report in PDF format we need to use the ‘Format’ parameter as shown In Figure 16.25.

Reports Interview Questions in .NET chapter 16 img 24

If we want to pass parameters to the report we can do something as shown in the figure ‘Pass parameters to the report’. In this scenario, we have passed the ‘Category’ parameter as shown in Figure

Reports Interview Questions in .NET chapter 16 img 25

Consuming reporting services Web service: if you look at the architecture of reporting service all reports are exposed through XML, i.e., Web services. You can see the Web service using this URL HTTP: //localhost/ReportServer/ReportService2005.asmx. In localhost, you need to put the server name or IP (Internet Protocol) address. So below are the steps to display reports using Web service.
Step 1 -> First add the Web service using HTTP: //localhost/ReportServer/ReportService2005.asmx in vourASP.NET project.
Step 2 -> We need to consume the Web service and use it. Figure 16.27 shows how the reporting service object is used.
1 -> You can see the Web service references to ‘ReportServicei005.asmx’.
2 -> We have named the Web service ‘Localhost’, so you can see we have imported the Web service.
3 -> We need to create an object of the ‘ReportingService2005’ class.
4 -> We need to set the credentials of the reporting object.
5 -> In this we will display which reports are present in the reporting server database. So we use the ‘ Listchildren’ method to get the reports from the Web service and then loop to display the same.
6 -> This sample code should display the reports present in the reporting service.

Reports Interview Questions in .NET chapter 16 img 26

The above example as shown in Figure 16.27 is a sample of how to use the reporting Web service. If you want to get how many input parameters the report has we need to use the ‘GetReportParameters’ method, if we want to display the report we use the ‘Render’ function. There are many other functions and methods which we have not discussed to keep the Chapter simple and to the point. Please experiment around the reporting Web service object for new methods and functions.

Reportviewer control: ASP.NET 2.0 comes with crystal report viewer control. You can drag and drop the control on the ASPX page and set the properties. Figure 16.28 shows how the ‘ReportViewer’ ^ Control looks like and how we can set the properties to view the report.

Reports Interview Questions in .NET chapter 16 img 27

Question 18.
Can you explain the difference between private and shared data sources?
The private data source is used by a single report only while shared data sources are shared between reports. As a practice, it is good to have a shared data source so if you want to change anything you need to change only on one data source.

Question 19.
How do reports caching in reporting services work?
As said previously reporting services has two main databases ‘ReportServer’ and ‘ReportServerTempDB’. Figure 16.29 shows how caching works in reporting services. The client first sends a request to the reporting service for the report. Reporting processor gets data from the database and the report format from the ‘report server database. Both these elements are then used to create an ‘Intermediate report format’. This intermediate format is saved in ‘ReportServerTempDB’. This intermediate format is for a particular user and for a session. So if the user generates the same report he will get a cached version. If the report is having parameters then there are different cached versions of the report for every parameter combination. Cached versions expire after a particular schedule when reports are modified, deleted, or redeployed.

Reports Interview Questions in .NET chapter 16 img 28

IN order to set the caching properties browse to a particular report using HTTP://localhost/reports/aclick on properties→ and go to the execution tab. Figure 16.30 ‘caching options’ shows different conditions on which you can define caching strategy.

Reports Interview Questions in .NET chapter 16 img 29

Question 20.
What are the major differences between Crystal and SQL reporting services?
Ease of hosting reports: Using the URL technology in RS (Reporting Services) we can host reports more easily than in crystal report where we need to make a Ul for the same.

Supporting platforms: Crystal can run on Windows, IBM (International Business Machines), and sun while RS (Reporting Services) can run only on Windows environments.

Client tools: In reporting services we have Business Intelligence (Bl) and development studio while in crystal its Report designer.

Caching: This is achieved in crystal by using cache server while in reporting services it’s stored as snapshots in the Report server database.

Export formats: in crystal, we have HTML, PDF, Excel, XML, Word, PDF, RTF (Rich Text Format), CSV, text files while in SQL Server 2005 we have all the formats above it also gives the capability to extend custom reporting formats.

Data sources: Crystal support more data sources while RS only supports Microsoft and oracle data sources. Crystal supports ADO (Active Data Objects), COM, Database excels Access, Exchange, NT, Xbase, JDBC (Java Database Connectivity), File system, and Paradox. RS supports only SQL Server, Oracle, ODBC (Open Database Connectivity), OLEDB and you can also extend additional data sources which do not exist in crystal reports.

Version issues: One of the main issues faced in the crystal is it has different versions which make it difficult to use, while RS comes with SQL Server minimizing the version issue.

Web server support: Crystal can run on IIS 5/6, Apache, Lotus, etc., while RS works only with IIS 5.0 and above.

Note: We have also shipped a PDF ‘SQLvsCrystaL WP.pdf’ which has been published by 
HTTP: // This PDF has very precise and detailed differences between 
crystal reports and SQL reporting services.

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?
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" ?>
<qty>12 </qty>

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?
“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?
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?
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?
Yes, they are case-sensitive.

Question 6.
What is the difference between XML and HTML?
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?
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?

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)?
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?
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?
If XML is confirming DTD rules then it is a valid XML.

Question 12.
What is the CDATA section in XML?
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?
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?
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?
“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?
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?

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

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

Question 1.
What is multi-tasking?
It is a feature of modern operating systems with which we can run multiple programs at same time, for example Word, Excel, etc.

Question 2.
What is multi-threading?
Multi-threading forms a subset of multi-tasking. Instead of having to switch between programs, this feature switches between different parts of the same program. Example you are writing in word and at the same time word is doing a spell check in background.

Question 3.
What is a thread?
A thread is a basic unit to which the operating system allocates processor time.

Question 4.
Did VB6 support multi-threading?
While VB6 supports multiple single-threaded apartments, it does not support a free-threading model, which allows multiple threads to run against the same set of data.

Question 5.
Can we have multiple threads in one App domain?
One or more threads run in an AppDomain. An AppDomain is a runtime representation of a logical process within a physical process. Each AppDomain is started with a single thread but can create additional threads from any of its threads.

Note: All threading classes are defined in System. Threading namespace.

Question 6.
Which namespace has threading?
‘ Systems. Threading’ has all the classes related to implement threading. Any .NET application which can implement threading has to import this namespace.

Note:NETprogram always has at least two threads running one is the main program and second is the garbage collector.

Question 7.
Can you explain in brief how can we implement threading?

Private Sub Forml_Load (ByVal sender As System. Object, ByVal e as
System.EventArgs) Handles MyBase.Load
Dim pthread1 As New Thread (AddressOf Thread1)
Dim pthread2 As New Thread (AddressOf Thread2) 
pthread1.Start ( ) 
pthread2.Start ()
End Sub
Public Sub Threadl ( )
Dim pint count As Integer
Dim pstr As String
Pstr = "This is first thread"
Do Until pint count > 5 
1stThreadDisplay.Items.Add (pstr) 
Pint count = pint count + 1
End Sub
Public Sub Thread2 ()
Dim pint count As Integer
Dim pstr As String
Pstr = "This is second thread"
Do Until pint count > 5 
1stThreadDisplay.Items.Add (pstr) 
Pint count = pint count + 1 
End Sub
Note: If you run the sample, you will see that sometimes the first thread runs first and then the second thread. 
This happens because of thread priorities. The first thread is run with highest priority.

Question 8.
How can we change the priority and what levels of priority are provided by .NET?
Thread Priority can be changed by using

Thread name.Priority = ThreadPriority.Highest

Following are different levels of Priority provided by .NET:

  • ThreadPriority.Highest
  • ThreadPriority.above normal
  • ThreadPriority.Normal
  • ThreadPriority.below normal
  • ThreadPriority.Lowest

Question 9.
What does the AddressOf operator do in the background?
The AddressOf operator creates a delegate object to the Background Process method. A delegate within VB.NET is a type-safe, object-oriented function pointer. After the thread has been instantiated, you begin the execution of the code by calling the start () method of the thread.

Question 10.
How can you reference the current thread of the method?
“Thread. CurrentThread” refers to the current thread running in the method. “CurrentThread” is public static property.

Question 11.
What is Thread.Sleep ( ) in threading?
Thread’s execution can be paused by calling the Thread. sleep method. This method takes an integer value that determines how long the thread should sleep. For example, Thread.CurrentThread. Sleep(2000).

Question 12.
How can we make a thread sleep for the infinite period?
You can also place a thread into the sleep state for an indeterminate amount of time by calling Thread. Sleep (System.Threading.Timeout. Infinite). To interrupt this sleep you can call the Thread. Interrupt method.

Question 13.
What is Suspend and Resume in Threading?
It is similar to Sleep and Interrupt Suspend allows you to block a thread until another Thread calls Thread. Resume. The difference between Sleep and Suspend is that the latter does not immediately place a thread in the wait state. The thread does not suspend until the NET runtime determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait state.

Note: In threading interviews, most people get confused with Sleep and Suspend. They look very similar.

Question 14.
What is the way to stop a long-running thread?
Thread. Abort ( ) stops the thread execution at that moment itself.

Question 15.
How do I debug the thread?
This window is only seen when the program is running in debug mode. In windows, one of the Windows is “Threads” (See Figure 17.1).

Threading Interview Questions in .NET chpter 17 img 1

Question 16.
What is Thread. Join ( ) in threading?
There are two versions of Thread join-

  • Thread, join ( ).
  • Thread. join (Integer) returns a Boolean value.

The Thread. join method is useful for determining if a thread has been completed before starting another task. The Join method waits a specified amount of time for a thread to end. If the thread ends before the time-out, Join returns true; otherwise, it returns False. Once you call Join, the calling procedure stops and waits for the thread to signal that it is done.

For example, you have “Thread1” and “Thread2” and while executing ‘Thread1″ you call “Thread2 .Join ( ) “.So “Thread1” will wait until “Thread2” has completed its execution and again invoke “Thread1”.

Thread. Join (Integer) ensures that threads do not wait for a long time. If it exceeds a specific time, which is provided in integer the waiting thread will start.

Question 17.
What are Daemon threads and how can a thread be created as Daemon?
Daemon thread’s run in the background and stops automatically the program is not running. An example of a Daemon thread is ‘Garbage collector’. The garbage collector runs until some .NET code is running or else it is idle.
You can make a thread Daemon by

Thread, Isbackground-true

Question 18.
How is shared data managed in threading?
There are certain situations that you need to be careful with when using threads. If two threads (e.g. the main and any worker threads) try to access the same variable at the same time, you’ll have a problem. This can be very difficult to debug because they may not always do it at exactly the same time. To avoid the problem, you can lock a variable before accessing it. However, if the two threads lock the same variable at the same time, you will have a deadlock problem. To avoid dead lock we need to use the ‘ SyncLock’ keyword as shown in the code snippet below.

SyncLock x
         'Do something with x 
End SyncLock

Question 19.
Can we use events with threading?
Yes, you can use events with thread; this is one of the techniques to synchronize one thread with other.

Question 20.
How can we know a state of a thread?
“Threadstate” property can be used to get the detail of a thread. Thread can have one or a combination of status. ‘System.Threading.Threadstate’ enumeration has all the values to detect a state of the thread. Some sample states are running, isAlive, suspended, etc.

Question 21.
What is the use of interlocked class?
The interlocked class provides methods by which you can achieve the following functionalities:

  • Increment Values
  • Decrement values
  • Exchange values between variables
  • Compare values from any thread. in a synchronization mode Example: System.Threading.Interlocked.Increment(IntA)

Question 22.
What is a monitor object?
Monitor objects are used to ensure that a block of code runs without being interrupted by code running on other threads. In other words, code in other threads cannot run until code in the synchronized code block has finished. SyncLock and End SyncLock statements are provided in order to simplify access to monitor objects.

Question 23.
What are wait handles?
Wait handles send signals of a thread status from one thread to another thread. There is three kinds of wait modes:

  • WaitOne
  • WaitAny
  • WaitAII

When a thread wants to release a Wait handle it can call the set method. You can use Mutex (mutually exclusive) objects to avail for the following modes. Mutex objects are synchronization objects that can only be owned by a single thread at a time. Threads request ownership of the mutex object when they require exclusive access to a resource. Because only one thread can own a mutex object at any time, other threads must wait for ownership of a mutex object before using the resource.

The WaitOne method causes a calling thread to wait for ownership of a mutex object. If a thread terminates normally while owning a mutex object, the state of the mutex object is set to be signaled and the next waiting thread gets ownership

Question 24.
What is ManualResetEvent and AutoResetEvent?
Threads that call one of the wait methods of a synchronization event must wait until another thread signals the event by calling the Set method. There are two synchronization event classes. Threads set the status of ManualResetEvent instances to signaled using the Set method. Threads set the status of ManualResetEvent instances to no signaled using the Reset method or when control returns to a waiting WaitOne call. Instances of the AutoResetEvent class can also be set to signal using Set, but they automatically return to non signaled as soon as a waiting thread is notified that the event became signaled.

Question 25.
What is Reader-Writer Locks?
You may want to lock a resource only when data is being written and permit multiple clients to simultaneously read data when data is not being updated. The ReaderWriterLock class enforces exclusive access to a resource while a thread is modifying the resource, but it allows non-exclusive access when reading the resource. Reader-Writer locks are a good alternative to exclusive locks that cause other threads to wait, even when those threads do not need to update data.

Question 26.
How can you avoid deadlock in threading?
Good and careful planning can avoid deadlocks. There are so many ways Microsoft has provided by which you can reduce deadlocks example Monitor, Interlocked classes, Wait handles, Event raising from one thread to another thread, and using ThreadState property you can poll and act accordingly.

Question 27.
What is TPL (Task Parallel Library)?
TPL stands for Task Parallel Library. It’s introduced in .NET 4.0 framework to simplify threading.TPL is a set of APIs (Application Programming Interface) that sits on top of core threading and simplifies threading. When we use threading API directly you need to take care of pooling, ensure that the thread executes on multiple processors, data and task parallelism, etc. When you use TPL all these things are taken care of so that you concentrate on the work rather than these lower-level technical details.
TPL simplifies the following things from development aspect:

  • Thread pooling is taken care of internally.
  • TPL ensures that threads will execute on multiple processors.
  • Cancellation of threads made easier.
  • State management is simplified as compared to core threading.

All components of TPL (task parallel library) exist in the below namespace.

using System. Threading. Tasks;

To invoke a thread using TPL we need to use the below syntax. We need to create the object of task object to invoke a thread.

Task tsk = new Task(MyTask); // Run the task. 
tsk.Start( );

Question 28.
What is the difference between thread and process?
A thread is a path of execution that runs on a CPU (Central Processing Unit), a process is a collection of threads that share the same virtual memory. A process has at least one thread of execution, and a thread always runs in a process context.

Note: Its difficult to cover threading interview question in this small chapter. These questions can take only 
to a basic level. If you are attending interviews where people are looking for threading specialist, try to get 
deeper in to synchronization issues, as that is the important point they will stress.

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?
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?
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?
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?
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?
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?
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?
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">
<asp: ServiceReference Path="Customer.asmx" />
</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, 

Question 8.
Can you explain the concept of triggers in ‘UpdatePanel’ control?
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?
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?
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?
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?
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.


LINQ and Entity Framework 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 LINQ and Entity Framework

Question 1.
Define LINQ.
LINQ (Language Integrated Query Microsoft) is a uniform programming model for any kind of data access. It is also an OR-mapper that helps us to expedite our business object creation process.

LINQ enables you to query and manipulate data independently of data sources. Figure 13.1 shows how the .NET language stands over the LINQ programming model and works in a uniform manner over any kind of data source. It’s like a query language which can query any data source and any transform. LINQ also provides full type safety and compile time checking.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 1

LINQ can serve as a good entity for the middle tier. So it will sit in between the Ul and data access layer.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 2

Figure 13.2 shows a simple sample of LINQ. We have a collection of data ‘ objcountries’ to which LINQ will is making a query with country name can be any data source dataset, datareader,
XML, etc. Figure 13.2 shows how the ‘ Ob j Countries’ can be any can .of data. We then query for the ‘CountryCode’ and loop through the same.

Question 2.
How does LINQ help us from the perspective of business objects?
One of the tedious jobs in business objects is parsing and searching object collections. For instance, consider Figure 13.3 where we want to search a country by an ‘ID’ value. Each loop is used through the collection and gets the object. Many may argue how about keeping a key in List or Array. The below example is just a sample. For instance, if you want to search using country code and name, list / collection keys will not work with those multi-value searches.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 3

In other words, using LINQ, we can query business object collections and filter the collection in a single LINQ query.

Question 3.
Can you explain how a basic LINQ Query looks like?
Below is a simple LINQ query that selects all customer data from the ‘ Obj Customer’ collection.

from clsCustomer obj in objCustomer select obj

Question 4.
How do we write a LINQ query to search with criteria?
We need to put the where clause before the ‘ select’ keyword.

return from clsCustomer Obj in objCustomer where Obj.customerCode == “001 "select Obj;

Question 5.
How can do join using the LINQ query?
Below is the LINQ code snippet for creating joins between object collections. In this case, we are creating a join on customers and orders. If you remember the order collection was contained in the customer class.

return from clsCustomer ObjCust in objCustomer
from clsOrder ObjOrder in ObjCust.Orders
select ObjCust;

Question 6.
How can we do a group by using LINQ query?
Below is the code snippet which shows how group by query is written using LINQ. You can see we have created first a temp variable, i.e., ‘GroupTemp’ and then we have used the ‘Select’ clause to return the same.

var GroupCustomers = from ObjCust in objCustomer
                       group ObjCust by ObjCust.City into GroupTemp
select new (GroupTemp.Key, GroupTemp);

Question 7.
What are entity classes in LINQ?
Entity Glasses are classes that map to the table structure of your data source. Entity classes represent your business model. The class name of entity class map to table name using the ‘Table’ attribute while table column name map to properties of the class.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 4

Question 8.
How can we load the LINQ entity class?
The LINQ entity classes are loaded by using DataContext class as shown in Figure 13.5.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 19

Question 9.
How do we define 1-to-many and many-to-1 relationships in LINQ?
1-to-many relationships are defined by using EntitySet and many-to-1 is defined by using entity ref. Below is a sample code snippet that shows ‘ clsCustomer’ having many ‘CLS addresses

[Table(Name = "Customer")]
public class clsCustomer
       private EntitySet<clsAddresses> _CustomerAddresses;
       [Association(Storage = "_CustomerAddresses", ThisKey="CustomerId", 
       OtherKey = "Customerld")]
       public EntitySet<clsAddresses> Addresses
                 _CustomerAddresses = value;
                 return _CustomerAddresses;

If we need to define a one-to-one relationship we need to use the EntityRef attribute as shown in the below code snippet.

public class clsAddresses
       . . . .
       . . . .
       private EntityRef<clsPhone> _Phone;
       . . . .
       . . . .

Question 10.
How can we call a stored procedure using LINQ?
We can use the function attribute as shown in the below code snippet with the stored procedure name.

[Function(Name = "usp_SelectCustomer", IsComposable = false)]
public ISingleResult<clsCustomerEntity> getCustomerAll()
IExecuteResult objResult = this.ExecuteMethodCall(this,

Question 11.
How can we insert, update and delete using LINQ?
Insert, update and delete operations in LINQ are done by using ‘’ , ‘DeleteOnSubmit’ and ‘SubmitChanges’.
To add a new record using LINQ below is the code snippet.

DataContext objContext = new DataContext(strConnectionString);
clsCustomerEntity objCustomerData = new clsCustomerEntity();
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerName = txtCustomerName.Text;
objContext.GetTable<clsCustomerEntity>( ).InsertOnSubmit(objCustomerData);
obj Context.SubmitChanges( ) ;

Below is the code for updating a record by LINQ.

clsCustomerEntity objCustomerData =
(clsCustomerEntity)MyQuery.First<clsCustomerEntity>( );
objCustomerData.CustomerCode = txtCustomerCode.Text;
objCustomerData.CustomerMame = txtCustomerName.Text;
objContext.SubmitChanges( );

Below is the code for deleting records using LINQ,

objContext.GetTable<clsCustomerEntity>( ).DeleteOnSubmit(objCustomerData);
objContext. SubmitChanges( );

Question 12.
What are DBML files in LINQ?
DBML stands for Database Markup Language which is a XML file, in big projects we will have large number of tables, developing entity classes for those
tables will be very difficult. DBML files help to automate the creation of entity classes by simple drag-and-drop as shown in Figure 13.6.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 5

Question 13.
What is an Entity framework?
ADO.NET entity is a QRM (Object Relational Mapping) that creates a higher abstract object model overADO.NET components.
So rather than getting in to dataset, datatabies, command and connection objects as shown in the below code, you work on higher-level domain objects like customers, suppliers, etc.

DataTable table = adoDs.Tables [0];
for (int j = 0; j < table.Rows.Count; j++)
      DataRow row = table.Rows[j];
      // Get the values of the fields
      string CustomerName =
      string CustomerCode =

Below is the code of entity framework in which we are working on the higher-level domain objects like a customer rather than working with base-level ADO.NET components (like dataset, DataReader, command, connection objects, etc).

foreach (Customer objCust in obj. Customers)
{ }

Question 14.
So what are the benefits of using EF?
The main and the only benefit of EF (Entity Framework) it auto-generates code for Model (Middle layer), Data access layer, and mapping code thus reducing a lot of development time.

Question 15.
So what are the different ways of creating these domain/entity objects?
Entity objects can be created in two ways from a database structure or by starting from scratch by creating a model (See Figure 13.7).

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 6

Question 16.
What is pluralize and singularize in the Entity framework dialog box?
“Pluralize” and “Singuiarize” give meaningful naming conventions to the objects. In simple words it says do you want to represent your objects with the below-naming convention:

  • What does one Customer record mean? “Customer”(singular).
  • A lot of customer records means “Customer’s” ( plural, watch the “S”)

If you select the below check box entity framework generates a naming convention that adheres to plural and singular coding convention.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 7

Question 17.
What is the importance of the EDMX file in entity framework?

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 8

EDMX (Entity Data Model XML) is an XML file that contains ail mapping details of how your objects map with SQL table (See Figure 13.9). The EDMX file is further divided into three sections CSDL (Conceptual Schema Definition Language), SSDL (Software Schema Definition Language), and MSL (Mapping Schema Language).

Question 18.
Can you explain CSDL, SSDL and MSL sections in EDMX file?
CSDL (Conceptual Schema Definition Language) is the conceptual abstraction which is exposed to the application.
SSDL (Storage Schema Definition Language) defines the mapping with your RDBMS (Relational Database Management System) data structure. MSL (Mapping Schema Language) connects the CSDL and SSDL.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 9

Question 19.
What are T4 templates?
T4 (Text Template Transformation Toolkit) is a template-based code generation engine as shown in Figure 13,11. So you can go and write C# code in T4 templates (, tt is the extension) files, and those C# codes are executed to generate the file as written according to C# logic.
For instance the below T4 C# code:

<#@ template language=” C#” #>
Hello <# Write(“Worldl”) #>

Will generate the following C# output:

World !

Question 20.
So what is the importance of T4 in the Entity framework?
T4 files are heart in EF code generation. So the T4 code templates read the EDMX XML file and generate C# behind code. This C# behind code is nothing but your entity and context classes.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 10

If you create a project using Visual Studio 2012, you will see the hierarchy as shown in Figure 13.12 At the top we have the EDMX (Entity Data Model XML) file, followed by the TT or T4 file and then the .cs code file.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 11

Question 21.
How can we read records using entity framework classes?
In order to browse through records you can create the object of the context class and inside the context class, you will get the records.
For instance in the below code snippet we are looping through list of Customer object collection. This customer collection is an output given by the context class

CustomermytestEntities obj = new () ;
foreach (Customer objCust in obj.Customers)
{ }

Question 22.
How can we add, update and delete using EF?
Create the object of your entity class, add it to the data context using add object method and then call save changes method.

CustomermytestEntities obj = new CustomermytestEntities( ) ;
Customer objCust = new Customer( );
objCust.CustomerCode = "1001";
obj.SaveChanges( );

If you want to update, select the object, make change to the object and call accept changes.

CustomermytestEntities objContext = new CustomermytestEntities( );
Customer objCustomer = (Customer)objContext.Customers.FirstOrDefault( );
objCustomer.CountryCode = "NEP";
objContext.AcceptAllChanges( );

If you want to delete call the delete object method as shown in the below code snippet.

CustomermytestEntities objContext = new CustomermytestEntities();
Customer objCustomer = (Customer) );
objContext.DeleteObj ect(objCustomer);

Question 23.
People say the entity framework runs slow.
By default Entity framework has lazy loading behavior. Due to this default behavior, if you are loading a large number of records, and especially if they have foreign key relationships, you can have performance issues.
So you need to be cautious if you really need lazy loading behavior for all scenarios.
So for better performance disable lazy loading when you are loading a large number of records or use stored procedures.

Question 24.
Can you explain lazy loading in a detailed manner?
Lazy Loading is a concept where we load objects on demand rather than loading everything in one go.Consider a situation where you have 1 to many relationships between “Customer” and “Address” object. Now let’s say you are browsing the customer data but you do not want address data to be loaded that moment. But the time you start accessing the address object you would like to load address data from the database.

The entity framework has the lazy loading behavior by default enabled. For instance, consider the below code. When we are doing “foreach” on the customer object address object is not loaded. But the time you start doing “for each” on the address collection address object is loaded from SQL (Structured Query Language) Server by firing SQL queries.

So in simple words, if will fire a separate queries for each address record of the customer which is definitely not good for a large number of records.

MyEntities context = new MyEntities();
var Customers = context.Customers.ToList();
foreach (Customercust in Customers) // In this line no address object loaded
     foreach(Address add in cust.Addresses){}// Address object is loaded here

Question 25.
How can we turn off lazy loading?
The opposite of lazy loading is eager loading. In eager loading we load the objects beforehand. So the first thing is we need to disable lazy loading by setting “LazyLoadingEnabled” to false.

context. ContextOptions.LazyLoadingEnabled = false;

So now we have to explicitly tell EF what objects we want to load by using the “include” function. Below is a simple sample code where we tell EF to load customer as well as address objects by using the “include” function.
So now the customer object and the related address objects will be loaded in one query rather than multiple queries.

var employees = context. Customers.Include(“Addresses”). Take(5);

Question 26.
How can we use stored procedures in entity framework?
You can use the stored procedure mapping details in EDMX as shown in the Figure 13.13.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 12

Question 27.
What are POCO classes in Entity framework?
POCO means Plain Old C# Object. When EDMX creates classes they are cluttered with a lot of entity tags. For instance below is a simple customer class generated using an entity framework. Many times we would like to use simple .NET classes and integrate the same with entity framework.
The entity framework allows the same. In other words you can create a simple .NET class and use the entity context object to load your simple .NET classes.

Below is a simple class generated by EF which is cluttered with lot of EF attributes.

(NamespaceN ame ="CustomermytestModel",
[ Serializable( )]
public partial class Customer:
      #region Factory Method
      /// <summary>
      /// Create a new Customer object.
     /// </suinmary>
    /// <param name="id">Initial value of the Id property.</param>
   /// <param name="customerCode">Initial value of the CustomerCode
  /// <param name="customername">Initial value of the Customername
  public static Customer CreateCustomer(global: : System.Int32 id,
  global: : System.String customerCode, global: : System.String
         Customer customer = new Customer( );
         customer.Id = id;
         customer.CustomerCode = customerCode;
         customer.Customername = customername;
         return customer;
#region Primitive Properties

Question 28.
How to implement POCO in entity framework?
To implement POCO is a three-step process:

  • Go to the designer and make the code generation strategy to None. This step means that you would be generating the classes with your own hands rather than relying on EF auto code generation.
  • So now that we have stopped the auto generation of code, we need to create the domain classes manually. So add a class file and create the domain classes like the one “Customer” class we have created.
public class Customer
      private string _customerName;
      public string CustomerName;
            get { return _customerName; }
            set { _customerName = value; }
      private int _Customerid;
      public int Customerid
           get { return _Customerid; }
           set { _Customerid = value; }

Write your Context layer code inheriting from the “ObjectContext”. I his code you can copy paste from the behind code of EF also before disabling auto-generation.

public partial class Testl23Entities: ObjectContext
       public Testl23Entities( )
       : base("name=Testl23Entities", "Testl23Entities")
             this.ContextOptions.LazyLoadingEnabled = true;
       partial void OnContextCreated( ) ;
       public ObjectSet<Customer> Customers
                   if ( (_Customers == null) )
                         _Customers =
                         base.CreateObj ectSet<Customer>("Customers");
                   return Customers;
      private ObjectSet<Customer> _Customers;
      public void AddToCustomers(Customer customer)
              base.AddObject("Customers", customer);

And finally, you can use the above code in your client as you were using your EF normally.

Test123Entities oContext = new Test123Entities( );
List<Customer> oCustomers = oContext. Customers. ToList<Customer>( );

Question 29.
in POCO classes do we will need EDMX flies?
Yes, you will still need EDMX files because the context object reads the EDMX files to do the mapping.

Question 30.
What is the code first approach in entity framework?
In the code first approach, we avoid working with the visual designer of entity framework. In other words, the EDMX file is excluded from the solution. So you now have complete control over the context class as well as the entity classes.

Question 31.
What is the difference between POCO, code first, and simple EF approach?
All these three approaches define how much control you want on your Entity framework code. The entity framework is an OR-Mapper it generates lot of code, it creates your middle-tier (Entity) and Data access layer (Context).
But a lot of times you want to enjoy the benefits of both the world you want the auto-generation part to minimize your development time and also you want to control the code so that you can maintain code quality.

Below Is the difference table which defines each of the approaches. In the Simple entity framework, everything is auto generated and so you need the EDMX XML file as well. POCO is semi-automatic so you have full control over the entity classes but then the context classes are still generated by the EDMX file.
In code first you have complete control on how you can create the entity and the context classes. Because you are going to manually create these classes you do not have a dependency on the EDMX XML file, below is a simple table which shows the cross comparison.

EDMX Entity Context
Simple entity framework Needed Auto Auto
POCO approach Needed Manual Auto
Code First Not Needed Manual Manual

Question 32.
How can we handle concurrency in Entity framework?

Note: Before this question interviewer can ask you about What is concurrency and What is pessimistic 
and optimistic locking. Please do refer ADO.NET Chapter for the same.

In EF concurrency issue is resolved by using optimistic locking. PleasereferADO.NET Chapter for What is optimistic locking and pessimistic locking?. To implement optimistic locking right click on the EDMX designer and set the concurrency mode to “Fixed” as shown in the Figure 13.14.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 13

Now whenever we have concurrency issues you should get an “OptimisticConcurrency Exception” error as shown in Figure 13.15. You can then put a try / catch to handle this situation.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 14

Question 33.
How can we do pessimistic locking in the Entity framework?
We cannot do pessimistic locking using the entity framework. You can invoke a stored procedure from entity framework and do pessimistic locking by setting isolation level in the stored procedure. But direct entity framework does not support pessimistic locking.

Question 34.
What are ciientwins and store wins mode in entity framework concurrency?
Clientwins and store wins are actions which you would like to take when concurrency happens. In store wins / database wins the data from the server is loaded into your entity objects. Client wins is opposite to storedwins, data from the entity object is saved to the database.
We need to use the “Refresh” method of the entity framework context and provide the “RefreshMode” enum values. Below is a simple code snippet that executes “Clientwins”.

Context. Refresh (System. Data. Objects. RefreshMode. Clientwins, Obj);

Question 35.
What are scalar and navigation properties in the Entity framework?

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 15

Scalar is properties whose actual values are contained in the entities. For example, in the above customer entity “Customer name” and “Customer id” are scalar properties. Normally a scalar property will map to a database field.

Navigation Properties heip to navigate from one entity to the other entity. For instance consider the below example in which we have two entities customer and address and one customer has multiple address objects.

Now we would like to have a facility where at any given moment we would like to browse from a given customer object to the addresses collection and from address object to the customer.

If you open the entity designer you would notice “Navigation” Properties as shown in Figure 13.16. The navigation properties are automatically created from the primary and foreign key references.
So now because of those navigation properties we can browse from Customer to Addresses object, look at the below code.

Customer Cust = oContext.Customers.ToList<Customer>()[0];
// From customer are browsing addresses
List<Address> Addresses = Cust.Addresses.ToList<Address>( );

You can also go vice-versa. In other words from the Address object you can reference the Customer object as shown in the below code.

Address myAddress = Addresses[0];
// From address we can browse customer
Customer cus = myAddress.Customer;

Question 36.
What are complex types In the Entity framework?
There can be situations where you have common properties across entities. For example, consider Figure 13.17 where we have “Customer” and “Supplier” entities. They have three fields in common “Address 1”, “Address2” and “Phoneno”. These fields have been duplicated both in “Customer” as well as “Supplier” entities.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 16

So to remove these duplicate and redundant fields we can move them, to a common complex type called “Address”. So complex. types group common fields so that they can be reused across entities.

So to create a complex type, select the fields which you want to group in a complex type. Below is Figure 13.18 which shows the same. Once the complex type is created you can then reuse the complex type with other entities as well.

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 17

Question 37.
What is the difference between “DbContext” and “ObjectContext”?
“DbContext” is a wrapper around “ObjectContext”, it is a simplified version of “ObjectContext” (See Figure 13.19).

LINQ and Entity Framework Interview Questions in .NET chapter 13 img 18

So as a developer you can start with “DbContext” as It is simple to use. When you feel that some of the operation cannot be achieved by “DbContext” you can then access “ObjectContext” from “DbContext” object as shown in the below code:


Note: If the interviewer is asking what kind of operations are not supported in “DbContext”, you can excuse by saying do not remember upfront. Wonder why sometimes the interviewer asks API (Application Programming Interface) level questions?

Question 38.
What’s the difference between LINQ to SQL and Entity framework?

  • LINQ to SQL is good for rapid development with SQL Server. EF is for enterprise scenarios and works with SQL servers as well as other databases.
  • LINQ maps directly to tables. One LINQ entity class maps to one table. EF has a conceptual model and that conceptual model maps to the storage model via mappings. So one EF class can map to multiple tables or one table can map to multiple classes.
  • LINQ is more targeted towards rapid development while EF is for the enterprise level where the need is to develop the loosely coupled framework.

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

Question 1.
What is WPF?
WPF (Windows Presentation Foundation) is a graphical subsystem for displaying user interfaces, documents, images, movies, etc., in windows applications.

Question 2.
What is the need for WPF when we had Windows forms?

Remember: ABCDEFG

A – Anywhere execution (Windows or Web)
B – Bindings (less coding)
C – Common look and feel (resource and styles)
D – Declarative programming (XAMLor Extensible Application Markup Language) E – Expression blend animation (Animation ease)
F – Fast execution ( Hardware acceleration)
G – Graphic hardware-independent (resolution independent)

Question 3.
What is XAML in WPF and why do we need it?
XAML is an XML file that represents your WPF Ul. The whole point of creating the Ul representation in XML was to write once and run it anywhere. So the same XAML Ul can be rendered as a windows application with WPF and the same Ul can be displayed on the browser using the WPF browser or Silverlight application.

WPF Interview Questions in .NET chapter 12 img 1

Question 4.
What is xmlns in XAML file?
“xmlns” stands for XML namespaces. It helps us to avoid name conflicts and confusion in XML documents. For example, consider the below two XML which have table elements, one table is a HTML table and the other represents a restaurant table. Now if both these elements name conflicts and confusion.


So to avoid the same we can use XML namespaces. You can see in the below XML we have qualified the HTML table with “<h: table>” and the restaurant table element qualified with “<r: table>”.

<h: tablexmlns : h="HTTP: //www.w-3 . org/TR/html4/">
</h: table>

<r: tablexmlns: h="HTTP: //"> <cloth>red</cloth>
</r: table>

Question 5.
What is the difference between xmlns and xmlns: x in WPF?
Bothe namespaces help to define/resolved XAML Ul elements.
The first namespace is the default namespace and helps to resolve overall WPF elements.

xmlns="HTTP: //schemas, microsoft. com/winfx/2006/xaml/presentation ”

The second namespace is prefixed by “x: ” and helps to resolve XAML language definition.

xmlns: x=”HTTP: //!”

For instance for the below XAML snippet, we have two things one is the “StackPanel” and the other is “x: name”. “StackPanel” is resolved by the default namespace and the “x: name” is resolved by using “xmlns: x” namespace. ,

<StackPanelx: Name-’myStack”/>

Question 6.
Provide some instances where you have “xmlns: x” namespace in XAML?
There are two common scenarios where we use “xmlns: x” namespace:
To define behind code for the XAML file using “x: class” attribute.

          xmlns="HTTP: //"
          xmlns: x="HTTP: //" 
          x: Class="MyNamespace.MyCanvasCodelnline"

Second to provide name to an element.

<StackPanel x: Name=”myStack” />

Question 7.
When should we use “x: name” and “name”?
There is no difference between “x: name” and “name”, “name” is shorthand of “x: name”. But in classes where you do not find “name” property (this is a rare situation), we need to use “x: name” property.

Question 8.
What are the different kinds of controls in WPF?
WPF controls can be categorized into four categories:

• Control: This is the basic control with which you will work most of the time. For example textbox, buttons, etc. Now controls that are standalone control like buttons, text box, labels, etc., are termed as content control. Now there are other controls that can hold other controls, for instance, items controls. Itemscontroi can have multiple textbox controls, label controls, etc.

• Shape: These controls help us to create simple graphic controls like Ellipse, Line, rectangle, etc.

• Panel: These controls help to align and position the controls. For instance, the grid helps us to align in a table manner, stack panel helps for horizontal and vertical alignment.

• Content presenter: This control helps to place any XAML content inside it. Used when we want to add dynamic controls on a WPF screen.

All the above four types of WPF controls finally inherit from the framework element class of WPF as shown in Figure 12.2.

WPF Interview Questions in .NET chapter 12 img 2

Can you explain the complete WPF object hierarchy?

WPF Interview Questions in .NET chapter 12 img 3

Figure 12.3 shows the hierarchy of WPF objects as shown in Figure 12.3.

Object: As WPF is created using .NET so the first class from which WPF Ul classes inherits is the .NET object class.

Dispatcher: This class ensures that all WPF Ul objects can be accessed directly only by the thread who owns him. Other threads who do not own him have to go via the dispatcher object.

Dependency: WPF Ul elements are represented by using XAML which is XML format. At any given moment of time a WPF element is surrounded by other WPF elements and the surrounded elements can influence this element and this is possible because of this dependency class. For example, if a textbox is surrounded by a panel, it’s very much possible that the panel background color can be inherited by the textbox.

Visual: This is the class that helps WPF Ul to have their visual representation.

Ul Element: This class helps to implement features like events, input, layouting, etc.

Framework element: This class supports templating, styles, binding, resources, etc.
And finally, all WPF controls textbox, buttons, grids, and whatever you can think about from the WPF toolbox inherits from the framework element class.

Question 9.
Does that mean WPF has replaced DirectX?
No, WPF does not replace DirectX. DirectX will still be needed to make cutting-edge games. The video performance of directX is still many times higher than WPF API (Application Programming Interface). So when it comes to game development the preference will be always DirectX and not WPF. WPF is not an optimum solution to make games, oh yes you can make a TIC-TAC-TOE game but not high-action animation games.

One point to remember WPF is a replacement for Windows form and not directX.

Question 10.
So is XAML meant only for WPF?
No, XAML is not meant only for WPF. XAML is an XML-based language and it had various variants.

WPF XAML is used to describe WPF content, such as WPF objects, controls, and documents. In WPF XAML we also have XPS XAML which defines an XML representation of electronic documents.

Silverlight XAML is a subset of WPF XAML meant for Silverlight applications. Silverlight is a cross¬platform browser plug-in that helps us to create rich Web content with 2-dimensional graphics, animation, and audio and video.

WWF XAML helps us to describe Windows Workflow Foundation content. WWF engine then uses this XAML and invokes workflow accordingly.

Question 11.
Can you explain the overall architecture of WPF?

WPF Interview Questions in .NET chapter 12 img 4

Figure 12.4 shows the overall architecture of WPF. It has three major sections presentation core, presentation framework, and mallcore. In the same diagram, we have shown how other sections like direct and operating systems interact with the system. So let’s go section by section to understand how every section works.

User32: It decides which goes where on the screen.

DirectX: As said previously WPF uses DirectX internally. DirectX talks with drivers and renders the content.

MILcore: MIL stands for media Integration library. This section is an unmanaged code because it acts like a bridge between WPF managed and DirectX / User32 unmanaged API.

Presentation core: This is a low-level API exposed by WPF providing features for 2D (two-dimensional), 3D (three-dimensional), geometry, etc.

Presentation framework: This section has high-level features like application controls, layouts. Content, etc., helps you to build up your application.

Question 12.
What is App.xaml in the WPF project?
App.xaml is the start-up file or a bootstrapper file that triggers your first XAML page from your WPF project.

Question 14.
What are various ways of doing alignment in WPF?
There are five ways of doing alignment in WPF as shown in Figure 12.5:
Grid: In Grid alignment we divide the screen in to static rows and columns like HTML tables and position elements in those rows and column area.

<ColumnDefinition />
<ColumnDefinition />
<RowDefinition />
<RowDefinition />
<Label Grid.Column="0" Grid.Row="0" Background="Red">lst column 1st row </Label>
<Label Grid.Column="l" Grid.Row="0" Background="LightGreen">2nd Column 2nd row</Label>
<Label Grid.Column="0" Grid.Row="1" Background="Red">lst column 2nd row</ Label>
<Label Grid.Column=''l" Grid.Row="l" Background= "LightGreen">2nd Column 2nd row</Label> 

Stack panel: Arranges control in vertical or horizontal format as shown in Figure 12.6.

<StackPanel Orientation="Vertical">
<Label Background="Red">Red </Label>
<Label Background="LightGreen">Green </Label>
<Label Background="LightBlue">Blue </Label>
<Label Background="Yellow">Yellow </Label>

WPF Interview Questions in .NET chapter 12 img 5

Wrap panel: Aligns elements in a line until the border is hit, then wraps into the next line as shown in Figure 12.7.

<WrapPanel Orientation="Horizontal">
<Label Width="125" Background="Red">Red 1</Label>
cLabel Width="100" Background="LightGreen">Green 1</Label>
<Label Width="125" Background="LightBlue">Blue 1</Label>
<Label Width="50" Background="Yellow">Yellow 1</Label>
<Label Width="150" Background="Orange">Orange 1</Label>
<LabeI Width="100" Background="Red">Red 2</Label>
<Label Width="150" Background="LightGreen">Green 2</Label>
<Label Width="75" Background="LightBlue">Blue 2</Label>

WPF Interview Questions in .NET chapter 12 img 6

Dock Pane1:Aligns controls in five different regions: top, bottom, left, right and center as shown in Figure 12,8.

<Label DockPanel.Dock="Top" Height="100" Background="Red">Top 1</Label> 
<Label DockPanel. Dock=''Lef t" Background^"LightGreen">Lef t</Label>
<Label DockPanel.Dock="Right" Background="LightCyan">Right</Label>
<Label DockPanel.Dock="Bottom" Background="LightBlue">Bottom</Label> 
<TextBlock VerticalAlignment="Center" HorizontalAlignment="Center"> Demo of Dock panel</TextBlock>

WPF Interview Questions in .NET chapter 12 img 7

Canvas: Positions elements absolutely use co-ordinates as shown in Figures 12,9,

<Canvas Margin="273, 130, 144, 99">
<TextBlock> Canvas position </TextBlock>

Question 15.
What are resources in WPF?
Resources are objects referred to in WPF XAML, In the C# code when we create an object, we do the following three steps as shown in Figure 12,10.

WPF Interview Questions in .NET chapter 12 img 8

using CustomerNameSpace; // import the namespace.
Customer obj = new Customer( ); // Create object of the class
Textboxl. text = obj . CustomerCode; // Bind the object with UI elements

So even in WPF XAML to define resources that are nothing but objects we need to the above 3 steps:

  • Import namespace where the class resides: To define namespace we need to use the “xmlns” attribute as shown in the below XAML code.
<Window x: Class="LearnWpfResources.MainWindow"
xmlns = "HTTP: // 006/xaml/presentation
xmlns: x="HTTP: //"
xmlns: custns="clr-namespace: LearnWpfResources"
Title="MainWindow" Height="350" Width="525">
  • Create an object of the class: To create an object of the class in XAML we need to create a resource by using the resource tag as the below code. You can the object name is ‘ custobj “.
<custns: Customer x: Key="custobj"/>

The above code you can map to something like this in C#.

Customer custobj = new Customer( );
  • Bind the object with Ul objects: Once the object is created we can then bind them using bindings like one way, two way as explained in “Explain one way, two way, one time and one way to the source?” question explained above.
<TextBox Text=”{Binding CustomerCode, Mode=TwoWay, Source={StaticResource custobj}}”/>

Question 16.
Explain the difference between static and dynamic resources.
Resources can be referred statically or dynamically. Static referred resources evaluate the resource only once and after that if the resources change those changes are not reflected in the binding. While dynamic referred resources are evaluated every time the resource is needed.

Consider the below “SolidColorBrush” resource which is set to “LightBlue” color.

<Window. Resources>
<SolidColorBrush Color="LightBlue" x: Key="buttonBackground" />

The above resource is bound with the below two textboxes statically and dynamically, respectively.

<TextBox Background=”{DynamicResource buttonBackground}”/> 
<TextBox Background=”{StaticResource buttonBackground}”/>

Now if we modify the resource, you see the first text box changes the background and the other textbox color stays as it is.

private void Button_Click(object sender, RoutedEventArgs e)
     Resources["buttonBackground" ] = Brushes.Black;

WPF Interview Questions in .NET chapter 12 img 9

Figure 12.11 shows the output of the same.

Question 17.
When should we use static resources over dynamic resources?
Dynamic resources reduce application performance because they are evaluated every time the resource is needed. So the best practice is to use Static resources until there is a specific reason to use dynamic resources. If you want resources to be evaluated again and again then only use dynamic resources.

Question 18.
Explain the need for binding and commands.
WPF bindings helps to send/receive data between WPF objects while command helps to send and receive actions as shown in Figure 12.12. The object that emits data or action is termed as the source and the object who wants to receive data or action is termed as a target.

WPF Interview Questions in .NET chapter 12 img 10

Question 19.
Explain one way, two way, one time, and one way to the source.
All the above four things define how data will flow between target and source objects when WPF binding is applied as shown in 12.13.

WPF Interview Questions in .NET chapter 12 img 11

Two ways: Data can flow from both source to target and from target to source.
One way: Data flows only from source to target.
One way to source: Data flows only from target to source.
One time: Data flows only for the first time from source to target and after that, no communication happens.
The table below shows is an easy tabular representation to memorize the same.


Data flow

Target to Source Source to target
Two way Yes Yes
One way to source Yes No
One way No Yes
One time No For first Yes

Question 20.
Can you explain the WPF command with an example?
When end users interact with the application they send actions like button click, right-click, Ctrl + C, Ctrl + V, etc. A command class in WPF wraps these end-user actions into a class so that they can be reused again and again.
WPF Command class idea is an implementation of a command pattern from a gang of four design patterns.
To create a command class we need to implement the “command” interface. For example below is a simple command class that increments a counter class by calling the “increment” method.

WPF Interview Questions in .NET chapter 12 img 12

public class IncrementCounter:
      private clsCounter obj;
      public IncrementCounter
      (clsCounter o)
            obj = o;
      public bool CanExecute
      (object parameter)
           return true;
      public event EventHandler
      public void Execute(object parameter)
         obj.Increment( );

The command class needs two implement methods as shown in the above code:

What to Execute (Execute) – Command class is all about wrapping actions of end-users so that we can reuse them. At the end of Figure 12.14: Binding Direction day Action invokes methods. Mean for instance a “btnmaths_click” action will invoke the “Add” method of a class. The first thing we need to specify in the command class is which method you want to execute. In this case we want to call the “increment” method of “counter” class.

When to execute (CanExecute) – The second thing we need to specify is when the command can execute, which means validations. This validation logic is specified in the “CanExecute” function. If the validation returns true then “Execute” fires or else the action has no effect. You can see the code of “CanExecute” and “Execute” in the above code snippet.

Once you have created the “Command” class you can bind this with the button using the “Command” property as shown in the below XAML code.”CounterObj” is a resource object.

<Button Command=”{Binding IncrementClick, Source={StaticResource Counterobj}}”/>

So now that the action is wrapped in to command we do not need to write method invocation code again and again in behind code, we just need to bind the command object with the WPF Ul controls wherever necessary.

Question 21.
How does “UpdateSourceTrigger” affect bindings?
“UpdateSourceTrigger” decides when the data should get updated between WPF objects that are binded. In other words should data get updated in lost focus event, in data change event, etc

There are four modes by which “UpdateSourceTrigger” can be defined:

  • Default: If it is a text property then data is updated during lost focus and for normal properties data updates in property change event.
  • PropertyChanged: In this setting, data is updated as soon as the value is changed.
  • LostFocus: In this setting, data is updated as soon as the lost focus event occurs.
  • Explicit: In this setting, the data is updated manually. In other words, to update data between two WPF objects, you need to call the below code.
BindingExpression binding =txt1.GetBindingExpression(TextBox. TextProperty); binding. UpdateSource( );

To set “UpdateSourceTrigger” we need to use the “UpdateSourceTrigger” value which can be found in the bindings properties as shown in Figure 12.15.

WPF Interview Questions in .NET chapter 12 img 13

Question 22.
Explain the need for the “INotifyPropertyChanged” interface.
When we bind two WPF objects the target data is updated depending on the “UpdateSourceTrigger” events. Please refer to the previous question for “UpdateSourceTrigger” basics.

The “UpdateSourceTrigger” has events like lost focus, property change, etc. In other words, when lost focus or property change event happens on the target it makes a PULL to the source to get the latest data as shown in Figure 12.16.

WPF Interview Questions in .NET chapter 12 img 14

So it’s very much possible that the WPF source data has changed and because the WPF target “UpdateSourceTrigger” event did not fire it did not make a pull and the data of the source is not in sync with the target as shown in Figure 12.17. This is where the “INotifyPropertyChanged” interface comes to use.

WPF Interview Questions in .NET chapter 12 img 15

Below is a simple “clsCounter” class that has a “Counter” property and this property is incremented by the “Increment” method.

Now if we bind WPF label or textbox to the “Counter” property and call the “increment” method the new “Counter” value will not be propagated to the target. Because invoking a method does not trigger any “UpdateSourceTrigger” event.

So after calling the “increment” method the “Counter” value of the source and the target is out of synch.
To create a push event from the source you need to first implement the “iNotifyPropertyChanged” interface as shown in Figure 12.18. Now when someone calls the “increment” method you can raise an event saying that the “Counter” property has changed by calling the “PropertyChanged” function as shown in the below code.

In simple words, the source sends a notification to the target WPF object that data has changed in the source and if should refresh itself with the fresh data.

PropertyChanged(this, new PropertyChangedEventArgs(“Counter”));

Below is full “clsCounter” class code with “INotifyPropertyChanged” implemented.

public class clsCounter: INotifyPropertyChanged
     private int _Counter=0;
     public int Counter
          get { return _Counter; }
     public void Increment( )
         PropertyChanged(this, new PropertyChangedEventArgs("Counter"));
public event PropertyChangedEventHandler PropertyChanged;

Question 23.
How are WPF observable collections different from simple .NET collections?
Simple .NET collections do not notify the Ul automatically when elements are added or removed from them. So when we update simple .NET collection’s we need to send refresh events back to the WPF Ul for rebinding the collection.

“ObservableCollection” is a specialized collection that updates the Ul automatically and immediately when new elements are added and removed from the collection.

“ObservableCollection” implement’s “iNotifyCollectionChanged” interface. This interface exposes the “CollectionChanged” event which gets raised when elements are added or removed to the collection.

Below is a simple code which creates the “ObservableCollection” collection which is binded with a list.

ObservableCollection<Person> person = new ObservableCollection<Person>( ); 
IstNames.ltemsSource = person;

Question 24.
What are value converters in WPF?
Binding is one of the big features in WPF which helps us to facilitate data flow between WPF Ul and Object (See Figure 12.18). But when data flows from source to Ul or vice-versa using these bindings we need to convert data from one format to another format. For instance, let’s say we have a “Person” object with a married string property.

WPF Interview Questions in .NET chapter 12 img 16

Let’s assume that this “Married” property is binded with a check box. So if the text is “Married” it should return true so that the option check box look’s checked. If the text is “UnMarried” it should return false so that the option check box looks unchecked.

In simple words, we need to do data transformation. This is possible by using “Value Converters”. In order to implement value converters we need to inherit from the “value converter” interface and implement two methods “Convert” and “ConvertBack”.

public class MaritalConverter: IValueConverter
        public object Convert(object value, Type targetType, object parameter,
        System.Globalization.CultureInfo culture)
             string married = (string)value;
             if (married == "Married")
             return true;
            return false;
public object ConvertBack(object value. Type targetType, object
parameter, System.Globalization.Culturelnfo culture)
        bool married = (bool)value;
         if (married)
            return "Married";
            return "UnMarried" ;

You can see in the “Convert” function we have written logic to transform “Married” to true and from “UnMarried” to false. In the “ConvertBack” function we have implemented the reverse logic.

Question 25.
Explain multi-binding and multivalue converters in WPF?
“MultiBinding” helps you bind multiple sources to a target while multi-converters act like bridge – if the source and targets have different data formats or need some conversion as shown in Figure 12.19.

WPF Interview Questions in .NET chapter 12 img 17

For example, let’s say you have two textboxes that have “FirstName” and “LastName”. You want ~ that as soon as users type on .these two text boxes, the other text box should get updated with ‘ “FirstName LastName” as shown in Figure 12.20. s

Also vice-versa if we type in the third text box “FirstName LastName” it should display “FirstName” … and “LastName’ in the other two textboxes, respectively.

So the first thing is to create a multivalue converter class that will join “FirstName” and “LastName” into source and split “FirstName LastName” back to the target. For the same we need to implement “multivalue converter” and implement “Convert” and “ConvertBack” methods.

“Convert” helps to do the conversion from “Target” to “Source” and “ConvertBack” helps to ^ convert from “Source” to “Target”.

public class NameMultiConverter: IMultiValueConverter
public object Convert(object[ ] values. Type targetType, object
parameter, System.Globalization.Culturelnfo^ culture)
        // Conversion logic from Target to Source
public object[ ] ConvertBack(object value, Type[] targetTypes, object
parameter, System.Globalization.Culturelnfo culture)
       // Conversion logic from Source to Target.

Below is the “Convert” ( Target to Source) implementation where we get the “textbox” value in a array and we have concatenated the array values and returned the same in a single string. This single string will be displayed in the third textbox.

public object Convert(object[] values. Type targetType, object
parameter, System.Globalization.Culturelnfo culture)
      string x = " ";
      foreach (object y in values)
            x = x + " " + y.ToString( );
     return x;

“ConvertBack” helps to implement conversion logic from “Source” to “Target”. So when someone types “Shiv Koirala” in the third text box we would like to split “Shiv” in one string and “Koirala” in another string.

So you can see in the below code we have used the “Split” function to create a string array. So the first array index (array[0]) will go to the first textbox and the second array index (array[1]) will go to the second text box.

public object[ ] ConvertBack(object value, Type[ ] target types, object
parameter, System.Globalization.Culturelnfo culture)
      string str = (string)value;
      string[] val = str.Split(' ');
      return val;

Now once we are done with the converter next thing is to apply multi-binding. Below is the XAML code where we have the three text boxes ” txtFirstName”, ” txtLastName ” and “txtFirstAndLast”.

You can see how the “txtFirstAndLast” textbox “Text” is binded using multibinding element which binds to “txtFirstName” and “txtLastName” textbox . So now if you make changes to multiple target the single source gets updated and if you update the source multiple target gets updates.

<TextBox x: Name="txtFirstName" HorizontalAlignment="Left" Height="26"
Margin="42, 67, 0, 0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="152"/>
<TextBox x: Name="txtLastName" HorizontalAlignment="Lef t" Height="26"
Margin="41, 135, 0, 0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="153”/>
<TextBox x: Name="txtFirstAndLast"- Height="28" HorizontalAlignment="Left" Margin="239, 103, 0, 0" 
Name="label1" VerticalAlignment="Top" Width="117"> <TextBox.Text>
<MultiBinding Converter=”{StaticResource NameMultiConverter}">
<Binding ElementName="txtFirstName" Path="Text" />
<Binding ElementName="txtLastName" Path="Text" />

Question 26.
Explain WPF relative binding/relative resource.
When we define bindings we need at least two elements target and source. But many times rather than defining binding between two elements we would like to define binding with reference to the current element, i.e., relatively.

For instance, let’s say we have a WPF border and we would like the height and width of the border to be same. So for this scenario, the target and source are the same, the WPF border itself. So we can define the binding using “RelativeSource” as shown in the below code. You can see it uses the “Self” binding mode to bind the element to itself.

<Border BorderBrush="Black" BorderThickness = "l11 Height="139"
Width="{Binding Height, RelativeSource={RelativeSource Self}}"/>
What are the different ways of binding using relative sources?

There are four ways of binding relatively in WPF:

  • Self
  • Ancestor
  • Previous data
  • Templated parent

Question 27.
Can you explain self relative source binding in WPF?
This relative binding helps to bind one property of an element to the other property of the same element. For example, in the below XAML the border width is binded to a height of the same border element.

<Border BorderBrush-’Black” BorderThickness=”1" Height=”139"
Width=”{Binding Height, RelativeSource={RelativeSource Self}}”/>

Question 28.
Explain Ancestor relative source binding in WPF.
This relative binding helps to bind properties to the parent element properties. For example, in the below XAML code we have a textbox that has two borders as a parent. One border is having dark green and the other border is having dark red color as the border color.

WPF Interview Questions in .NET chapter 12 img 18

The dark green color border is the parent element followed by dark red and the textbox the child element at the end of the hierarchy.

<Border BorderBrush="DarkGreen"> 
<Border BorderBrush="DarkRed"> 
<TextBox />

Below is how the WPF application looks like when it runs.

Now we want the background color of the text box to be binded to one of the parent border colors. To achieve the same we can use ancestor relative binding.
Table below shows some important properties in Ancestor type binding we need to know before we writing the binding code.


So the relative binding code with ancestor level 1, i.e., red looks as shown below. In case you are confused with any of the properties please refer to the previous table for more information.

<TextBox Background="{Binding BorderBrush, RelativeSource={RelativeSource FindAncestor, AncestorLevel = l, 
AncestorType={x: Type Border}}}"/>

So now the complete XAML with parent border element looks as shown in the below code.

WPF Interview Questions in .NET chapter 12 img 19

<Border BorderBrush="DarkGreen"><! —
Level 2 ->
<Border BorderBrush="DarkRed" >< i —
Level 1 ->
<TextBox Background^' {Binding BorderBrush,
RelativeSource={RelativeSource FindAncestor, AncestorLevel=l,
AncestorType=(x: Type Border}}}"/>

Now if you run the above XAML code the textbox is binded with the background color of the first border. If you change the ancestor level to 2 textbox background color will change to green.

WPF Interview Questions in .NET chapter 12 img 20

Question 29.
Explain the difference between the visual and logical trees in WPF.
WPF Ul is represented in XAML which is an XML format. In XML elements are arranged in a hierarchal fashion. For example, if you look at the below XAML (it has been downsized for simplicity) we have a Window element, the window element has a Grid control and the grid control has a button inside it.


So if you visualize the above XAML logically you can think that the button control is a child element of the Grid and the grid is the child element of the Window. This relationship between the elements which looks logical looking at the XAML is termed as “Logical Tree” as shown in Figure 12.24.

WPF Interview Questions in .NET chapter 12 img 21

But now to display this Logical tree on to your screen you need lot of visual elements. Like border, text etc. So when you add these visual elements to the logical tree that complete structure is termed as “Visual Tree”.

Putting in simple words there is only tree in WPF but depending on how you view it these two trees are the outcome. If you use the WPF visualizer the above XAML tree looks something as shown in the below Figure 12.25 which is actually a complete visual tree.

WPF Interview Questions in .NET chapter 12 img 22

In simple words whatever you see in your XAML is a logical tree and to make it display it uses the visual tree. Figure 12.26 shows the logical and visual tree of the above XAML. Logical tree is without the shades and with shades is the visual tree.

Question 30.
Why do we need to have this perspective of visual and logical tree in WPF?
Visual tree and Logical tree are important when you work with WPF routed events.

Question 31.
Explain routed events in WPF.
Routed events are those events that travel up or down the visual tree hierarchy. WPF events can be classified into three types:

WPF Interview Questions in .NET chapter 12 img 23

Direct events: In this case event is raised at the source and handled at the source itself like “Mous enter” events.
Bubbling events: They travel up the visual tree hierarchy. For example, “MouseDown” is a bubbling event.
Tunneling events: These events travel down the visual tree hierarchy. “PreviewKeyDown” is a tunneling event.

Question 31.
Explain WPF styles.
Let’s say you have WPF Ul which has a lot of buttons and you want to set the background to “Aqua” color (See Figure 12.28).

So the quick way of doing this is to set the background of all the buttons to “Aqua” color as shown in the below XAML code. But now let’s say some days down the line customer wants to change the background color to “Red”. So you need to modify the background property for all buttons.

WPF Interview Questions in .NET chapter 12 img 24

<Button Backgrounds"Aqua"/>
<Button Background="Aqua"/>
<Button Background="Aqua"/>

Won’t it be great if we can define the background color as a style from some commonplace and when we want to change the background color we just change from that central commonplace That’s what WPF style helps us to achieve
WPF style helps to define look and feel (color, fonts, alignments, etc.) from a central location so that we can have ease of maintenance.
To define a style we need to use the “Style” tag of XAML. It needs three things at least:

  • X: Key: Name of Key of the style.
  • TargetType: WPF Ul object on which you want to apply the style. For example, in the below code we are applying this style on the button.
  • Setter: This element defines the property for which the value has to be set. For example, in our case, we are setting the “Background” color property to “Aqua”.
<Style x: Key="myStyle" TargetType="Button">
           <Setter Property="Background" Value="Aqua" />

Once the style is defined we can attach the style resource to the style property of the button element as shown in the below code.

<Button Style="{StaticResource myStyle}"/> 
<Button Style="{StaticResource myStyle}"/> 
<Button Style="{StaticResource myStyle}"/>

Question 32.
What are style triggers?
Many times we would want a style property to execute under certain conditions. Trigger’s help you to define conditions under which the style values will be set.

For example, we want to create a dynamic style where we focus on the button it should change to red color or else should be set to Aqua color as shown in Figure 12.29.

WPF Interview Questions in .NET chapter 12 img 25

To achieve the same we can use style trigger as shown in the below XAML code.

<Style x: Key="myStyle" TargetType="Button">
                     <Trigger Property="IsFocused" 
<Setter Property="Background" Value="Red"/>
             <Setter Property="Background" 
             Value="Aqua" />

Question 33.
Explain the Multitrigger concept in WPF.
Many times we want style triggers to be executed when multiple conditions are true. For example, let’s say we have a button we want the button background to be set to “RED” when there is focus on the button and when somebody moves the mouse on the button.

WPF Interview Questions in .NET chapter 12 img 26

In other situations, the background color should be set to “Aqua”.

So to achieve such multiple AND conditions we can use the “MultiTrigger” XAML element as shown in the below XAML code. Multiple AND conditions need to be defined in the “MultiTrigger .Conditions” tag and the property which needs to be modified in the “MultiTrigger. Setters” tag.

<Style x: Key="myStyle" TargetType="Button"> 
<Condition Property="IsFocused" Value="True" />
<Condition Property="IsMouseOver" Value="True" />
<Setter Property="Background" Value="Red" />
<Setter Property="Background" Value="Aqua" /> 

Question 34.
What is the difference between control templates and data templates?

WPF Interview Questions in .NET chapter 12 img 27

Control templates change the structure of a WPF element while data templates change the way data is displayed but maintain the structure of the WPF element.
A visual example of a control template where a rectangle-shaped button changes into an ellipse shape.
For that, we need to create a style using the “<ControlTemplate>” element. In this “<ControlTemplate>” WPF element we can define the structure which we want to apply to the element. Below is the XAML code for the same.

<Style TargetType="Button">
<!—Override all default style —>
<Setter Property="OverridesDefaultStyle" Value="True"/>
<Setter Property="Template">
<ControlTemplate TargetType="Button">
<Ellipse Fill=" (TemplateBinding Background-} "/>
cContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/ >

Later this style can be applied to the button using the style property as shown the below code.

<Button Style="{StaticResource mystyle}"/>

Data templates have no effect on the structure but they affect data. For example, Figure 12.32 shows the is list box on which data templates have been applied. You can see the structure of the list box does not change but the number of fields and the way they are placed is changed.

WPF Interview Questions in .NET chapter 12 img 28

To use data templates we need to use ‘ item template” tag and within the “item template” tag we can define how we want the data to be structured.

<ListBox Margin="26, 27, 165, 51" x: Name= "lstb">
<ColumnDefinition Width="150"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition> 
<TextBlock Grid.Column="0" Text = " {Binding Name}" FontSize="12" Height="18"/>
<TextBlock Grid.Column="l" Text="{Binding City}" FontSize="12" Height = "18"/>

Question 35.
What is MWM?
MVVM (Model-View-View Model) is an architecture pattern where we divide the project into three logical layers and every layer has its own responsibility (See Figure 12.33).

WPF Interview Questions in .NET chapter 12 img 29

Below are the three logical layers with an explanation of what they do:

• View: This layer handles the responsibility of taking inputs from the end-user, positioning of controls, look and feel, design, visuals, colors, etc.

• Model: This layer represents your middle layer objects like a customer, supplier, etc. It handles business logic and interaction with the data access layer.

• View Model: View model as it says View plus Model represents your user interface. You can also visualize this class as the behind code. This class is the bridge between model and view. It handles connection logic, data transformation logic, and action mapping between model and view. For example, it will have the following types of logic as shown below.

  • Replicating and propagating data between views and models. When someone enters data into Ul or the model gets updated this layer will ensure that the propagation of data happens between these entities.
  • Handling data transformation from view to model and vice-versa. For example, you have a model which has gender property with data as “M” for males and “F” for females. But on the View or Ul, you would like to display as a check box with true and false. This transformation logic is written in the view model class.
  • View model also maps Ul’s actions to methods. For example, you have “btn_Add” click event and when anyone clicks on this button you would like to invoke
    “Customer. Add ( )” method from the customer class. This connection code is again a part of the view model.

Question 36.
What are the benefits of MWM?
Below are the benefits of the MWM pattern as shown in Figure 12.34:

Separation of concern: As the project is divided into layers, every layer handles its own responsibility. This leads to better maintenance because when we change one layer the other layer does not get affected.

Increased Ul Reusability: The whole point of MWM is to remove behind, code, i.e., XAML.CS code. The problem with behind code is that it is tied up with Ul technology, for example, ASPX.CS code is tied up with the ASP page class, XAML.CS file is tied with WPF Ul technology and so on. So we cannotuseASPX.CS behind code with WPF XAML UI.

By moving the behind code to the view model class we can now use this with any Ul technology.

WPF Interview Questions in .NET chapter 12 img 30

Automated Ul Unit testing: View model class represents your Ul. The properties of the class represent Ul textboxes, combo boxes and the methods of the class represent action. Now as the Ul is represented by the view model class, we can do automated Ul testing using unit testing by creating the objects of view model class and doing the necessary assets.

Question 37.
What is the importance of command and bindings in the MWM pattern?
MWM is the most used architecture because of the command and bindings facility provided by WPF) (See Figure 12.35). WPF MWM is incomplete without command and bindings.

WPF Interview Questions in .NET chapter 12 img 31

Command and bindings help you to connect view (WPF Ul) with view model class without writing a lot of behind code. Binding connects the Ul input elements (textbox, combo box, etc.) with the view model class properties, and the Ul actions like button click, right-click are connected to the methods of the class by commands.

Note: Please refer to previous questions to understand commands and bindings.

Question 38.
What is the difference between MWM and 3-layer architecture?
MVVM has an extra layer as compared to 3 layer architecture. In 3 layer architecture, we have Ul (view), business logic (model), and Data Access Layer (DAL) as shown in Figure 12.36. In MWM we have an extra layer in between view and model, i.e., the view model class. 3 layer architecture complements MVVM architecture.

WPF Interview Questions in .NET chapter 12 img 32

Question 39.
Explain delegate command.
First, let us answer in short: “Delegate command makes an MVVM command class independent of the view mode!’. Now let’s understand the long way.
In MVVM architecture view talks with the view model and the view model talks with the model. When actions are sent from the view they are sent to WPF commands for handling the events as shown in Figure 12.37. WPF commands invoked methods of view model internally.
In other words, the command needs a reference of the view model class.

WPF Interview Questions in .NET chapter 12 img 33

If you see a typical WPF MVVM command it looks as shown below. You can see the “CustomerViewModel” class referenced inside the ‘btnCommand” class. If you think with your eyes closed this reference of the “CustomerViewModel” class inside the command is a problem. This will lead to tight coupling between command classes and the view model.
If you visualize the command it is nothing but clicks, double click, left mouse click, drag and drop, etc. It is an ACTION created by the user. Now wouldn’t be great if we can just attach this command with any view model. So like click event gets connected with ” Cus tomervi ewMode 1″ or “SupplierViewMode1”.
This is achieved by using the delegate command.

public class btnCommand: ICommand
Private CustomerViewModel Viewobj = new CustomerViewModel();
public btnCommand(CustomerViewModel obj)
Viewobj = obj;
public bool CanExecute(object parameter) // When he should execute
return Viewobj.IsValid( );
public void Execute(object parameter) // What to execute

To decouple the view model class from command we can use delegates, i.e., “Action” and “Func”.lf you see the command class we need only two things “WhattoExecute” and “WhentoExecute”. So how about passing these methods as generic delegates. You can see the constructor of “btnCommand” takes two delegates one what to execute and one when to execute.

You can see in the below code the “btnCommand” class has no reference of the view model class but has references to delegates which are just abstract pointers to functions/methods. So this command class can now be attached with any view model class. This approach is termed as “Delegate command”.

public class btnCommand: ICommand // Step 1: Create command
      private Action WhattoExecute;
      private Func<bool> WhentoExecute;
      public btnCommand(Action What, Func<bool> When)
             WhattoExecute = What;
             WhentoExecute = When;
     public bool CanExecute(object parameter) // When he should execute
            return WhentoExecute( );
     public void Execute(object parameter) // What to execute
           WhattoExecute( );

Question 40.
What is PRISM?
PRISM (Personal Record Information System Methodology) is a framework to develop a composite applications in WPF and Silverlight as shown in Figure 12.38. Composite applications are built using composition. In other words rather than building applications from scratch, we take prebuilt components, assemble them together and create the application.

WPF Interview Questions in .NET chapter 12 img 34

Take the example of simple WPF Ul (See Figure 12.39). You can see it has lots of sections. Now rather than building the whole Ul as one big unit, we can develop all these sections as an independent unit. Later by using PRISM we can compose WPF Ul by taking all these independent units (See Figure 12.39).

Question 41.
What are the benefits of PRISM?
Modular development: As we are developing components as independent units we can assign these units to different developers and do modular parallel development. With parallel development projects will be delivered faster.

High reusability: As the components are developed in individual units we can plug them using PRISM and create composed Ul in an easy way.

Question 42.
How are individual units combined into a single unit?
PRISM uses dependency injection for the same, please see the design pattern section to read about Dl (Dependency Injection). We can do Dl in two ways by using unity application block or MEF (Managed Extensibility Framework).

Question 43.
Does PRISM do MWM?
The prime focus of PRISM (Personal Record Information System Methodology) is modular development and not MWM. But it does have ready-made classes like delegate command which can help us reduce MWM code. But please note the main goal of PRISM was not MWM.

Question 44.
Is PRISM a part of WPF?
No, PRISM an acronym for (Personal Record information System Methodology) is a separate installation.

Question 45.
What is expression blend?
Expression blend is a designing tool for WPF and Silverlight applications.

Question 46.
What is Silverlight?
Silverlight is 16. Windows Presentation Framework (Vista Series) is a Web browser plug-in by which we can enable animations, graphics, and audio/video. You can compare Silverlight with Flash. We can view animations with Flash and it’s installed as a plug-in in the browser.

Question 47.
Can Silverlight run on platforms other than a window?
Yes, animations made in Silverlight can run on platforms other than window. In whatever platform you want to be run you just need the Silverlight plug-in.

Question 48.
Come on, even WPF runs under the browser why Silverlight?
Yes, there is something called a WPF browser application that can run WPF in the browser. For the WPF browser application, you need the .NET framework to be installed in the client location while for Silverlight you need only the plug-in. So in other words WPF browser applications are OS (Operating System) dependent while Silverlight is not. Silverlight plug-in can run in other OS other than windows while we all know .NET framework only runs in windows.


Question 49.
What is the relationship between Silverlight, WPF, and XAML?
As explained previously XAML is an XML file that defines the Ul elements. This XML file can be read by WPF framework or Silverlight framework for rendering. Microsoft first developed WPF and they used XAML files to describe the Ul elements to the WPF framework. Microsoft then extended WPF and made WPF/e (Windows Presentation Foundation/Everywhere) which helped to render the Ul in the browser. WPF/e was the code name for Silverlight. Later Microsoft launched Silverlight officially.

So the XAML just defines the XML structure to represent the Ul elements. Both the frameworks, i.e., WPF and Silverlight then read the Ul elements and renders the Ul elements in the respective platform as shown in Figure 12.40.

WPF Interview Questions in .NET chap

Question 50.
What is the XAP file in Silverlight?
XAP (Cross-Platform Audio Creation Tool Audio Projects) file is a compressed file that downloads all the necessary DLLs (Dynamic Link Library), code at the browser client so that the Silverlight application can run inside the browser.

Question 51.
Can you explain Silverlight architecture?
Before we talk about Silverlight architecture let’s discuss what is Silverlight is really made of technically. Silverlight has borrowed a lot of things from existing Microsoft technologies. We can think of Silverlight plug-in as a combination of some technologies from the core .NET framework, vector animations, media, and JavaScript as shown in Figure 12.41.

So we can visualize the Silverlight architecture as a combination of some functionalities from the core .NET framework, Ajax, and some functionalities like animation, media, etc., provided by the core Silverlight framework.

WPF Interview Questions in .NET chapter 12 img 36

We can think of Silverlight architecture as a combination of four important blocks:

• Some .NET framework components: Silverlight uses some components from the .NET framework. One of the main components is WPF. Many of the Ul components (check box, buttons, text boxes, etc.), XAML parsing, etc., are taken from the core WPF system. It also has taken components like WCF to simplify data access, it also has CLR (Common Language Runtime) for memory management, safety checking, and garbage collection. The base class libraries of NET are used for string manipulations, algorithms, expressions, collections, and globalization.

• Presentation core: The core presentation framework has functionalities to display vector 2d animations, images, media, DRM (Digital Rights Management), and handle inputs like mouse and keyboard.

• Other technologies: Silverlight interacts with other technologies like Ajax and JavaScript. So it also borrows some functionalities from their technologies.

• Hosting: Silverlight animations finally run under the browser environment. So it has a hosting functionality that helps to host the application the browser, expose a DOM (Document Object Model) by which JavaScript can manipulate the Silverlight components and it also has an installer functionality which helps to install Silverlight application and plug-in in the browser environment.
One of the things which you can notice from the architecture diagram is that the presentation core reads from the XAML file for rendering. The XAML is a component that is a part of the .NET framework and the rendering part is done by the presentation core (See Figure 12.42).

WPF Interview Questions in .NET chapter 12 img 37

The application is a typical HTML that runs under the browser. There are markups that instantiate the Silverlight plug-in. Now when the user interacts with the Silverlight application it sends an event to the JavaScript system or the .NET system. This depends on which programming language you are using. The program code which is either in JavaScript or .NET can make calls to the Silverlight run-time and achieve the necessary functionalities (See Figure 12.43). XAML will be read and parsed by the Silverlight runtime and then rendered accordingly to the browser.

WPF Interview Questions in .NET chapter 12 img 38

Question 51.
What are the various basic steps to make a simple Silverlight application?
This sample we are making using VS 2008 Web express edition and .NET 3.5. It’s a six-step procedure to run our first Silverlight application. So let’s go through it step by step.

Step1: The first thing we need to do is install Siiveriight SDK (Software Development Kit) from HTTP: //www. I vid = FB7900DB-4380-4B0F-BB95- 0BAEC714EE17&displavlanq=en

Step 2: Once you install the Silverlight SDK you should be able to use the Silverlight template. So when you go to create a new project you will see a ‘Siiveriight application’ template.

Step 3: Once you click ok you will see a dialog box as shown below with three options.

Add an ASP.NET Web project to the solution to host Silverlight: This option is the default option, and it will create a new Web application project that is configured to host and run your Silverlight application. If you are creating a new Silverlight application then this is the option to go.

Automatically generate Test Page To Host Siiveriight at build time: This option will create a new page at runtime every time you try to debug and test your application. If you want to only concentrate on your Silverlight application then this option is worth looking at.

Link This Siiveriight Control Into An Existing Website: If you have an existing Silverlight application then this option helps to link the Silverlight application with the existing Web application project. You will not see this option enabled for new projects, you need to have an existing Web application.

For this example, we have selected the first option. Once you click ok you should see the full IDE (Integrated Development Environment) environment for Silverlight

So let’s run through some basic points regarding the IDE view what we see. You will see there are two projects one is your Web application and the other is the Silverlight application. In the Silverlight application, we have two XAML files one is App.XAML and the other is Page.XAML.

App.XAML has global-level information.

Step 4: Now for simplicity’s sake, we just use the TextBlock tag to display a text. You can see as we type on the Page.XAML is displayed in the viewer.

Step 5: Now we need to consume the Silverlight application on an ASPX page. So in the HTML / ASPX page, we need to first refer to the Siiveriight namespace using the ‘Register’ attribute.

<%@Register Assembly=”System. Web. Siiveriight” Namespace-’System.Web.Ul.SilverlightControls” TagPrefix=’’asp” %>

We also need to refer the script manager from the Silverlight namespace. The script manager control is the functionality from AJAX. The main purpose of this control is to manage the download and referencing of JavaScript libraries.

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

Finally, we need to refer to the Silverlight application. You can see that in the source we have referred to the XAP file. XAP file is nothing but a compiled Silverlight application that is compressed and ZIP. It basically has all the files that are needed for the application in a compressed format. If you rename the file to ZIP extension you can open the same using WINZIP.

<asp: Siiveriight ID="Xainll" runat=" server" Source="~/ClientBin/ MyFirstSilverLightApplication.xap" 
MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />

So your final ASPX / HTML code consuming the Silverlight application looks something as shown below.

<%@ Page Language="C#" AutoEventWireup="true" %>
<%@ Register Assembly="System.Web.Silverlight"
TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "HTTP: //">
<html xmlns="HTTP: //" style="height: 100%;">
<head runat="server">
<body style="height: 100%,-margin: 0;">
<form id="forml" runat="server" style="height: 100%; ">
<asp: ScriptManager lD="ScriptManagerl" runat="server"x/asp: ScriptManager> <div style="height: 100%;">
<asp: Silverlight ID="Xamll" runat=”server" Source="~/ClientBin/MyFirstSilverLightApplication.xap"
MinimumVersion="2,0.31005.0" Width="100%" Height="100%" />

Step 6: So finally set the Web application as start-up and also set this page as start-up and run it. You should be pleased to see your first Silverlight application running as shown in Figure 12.44.

WPF Interview Questions in .NET chapter 12 img 39

Question 52.
What are the different kinds of bindings in Silverlight?
There is three kinds of bindings one-way, two-way, and one time-binding.

  • One-way binding: data flows from object to Ul and not vice-versa.
  • Two-way bindings: data flows from object to Ul and also vice-versa.
  • In one time binding data flows from the object to the Ul only once. There is no tracking mechanism to update data on either side. One-time binding has marked performance improvement as compared to the previous two bindings discussed. This binding is a good choice for reports where the data is loaded only once and viewed.

In order to specify bindings, we need to use the binding path attribute on the Ul elements as shown in the below code snippet.

<TextBox x: Name="txtEnterAge" Text="{Binding Path=Age, Mode=TwoWay}" Height="30" Width="150" 

Question 53.
How does Silverlight connect with databases?
If you remember the Silverlight architecture, it does not contain ADO.NET. In order to make insert, update, and deletes via Silverlight, we need to call WCF services, and WCF services in turn will do insert updates and deletes on SQL Server.

Question 54.
What are the two important points we noted when we call WCF service from Silverlight?

  • We can only WCF services asynchronously from Silverlight.
  • We need to create a cross-domain and client access policy XML (extensible Markup Language) file where the WCF service is hosted.

Question 55.
What are the different ways of doing alignment in Silverlight and WPF?
There are three ways provided by Silverlight for layout management Canvas, Grid, and Stack panel.

WPF Interview Questions in .NET chapter 12 img 40

Canvas is the simplest methodology for layout management. It supports absolute positioning using ‘X’- and ‘Y’-coordinates. ‘Canvas. Left’ helps to specify the X-coordinate while ‘Canvas. Top’ helps to provide the ‘Y’-coordinates.

Below is a simple code snippet which shows how Rectangle objects are positioned using ‘ Canvas ‘ on coordinates (50, 150).

<Canvas x: Name="MyCanvas">
<Rectangle Fill = "Blue" Widt.h="100" 

Grid layout helps you position your controls using rows and columns as shown in Figure 12.45. It’s very similar to table defined in HTML.
As the name so the behavior. Stack allows you to arrange your Ul elements vertically or horizontally.

WPF Interview Questions in .NET chapter 12 img 41

Question 56.
What is expression blend?
Expression blend is a graphic design tool that can design the look-and-feel using expression blend and give the XAML file to the developers who can write the behind code for the same.

Question 57.
How can we do multi-threading in WPF / Silverlight?
In order to implement proper multi-threading, we need to use the dispatcher object.

Question 58.
Can’t we just use threads, why do we need the dispatcher object?
In WPF / Silverlight objects have thread affinity. In other words, the objects can be modified only by the thread that has created the object. Now when any WPF/Silverlight applications run they run on the main thread as shown in Figure 12.47. So that main thread only has the permission to modify the same.

WPF Interview Questions in .NET chapter 12 img 42

Question 59.
But what if try to modify it?
If other threads who have not created the Ul object try to modify the same it will throw an exception “invalid cross-thread access”.
For example in the below code we have a simple function called as “Set value”, this function modifies a textbox. This function is called directly by creating a “Thread” object in a button click event.

private void buttonl_Click(object sender, RoutedEventArgs e)
       Thread obj = new Thread(new ThreadStart(SetValue));
       obj.Start( );
public void Setvalue( )
        for (int i = 0; i < 10; i++)
              textBoxl.Text = "test";

Now the Ul object “textbox1” is not created by thread “obj”. It’s created by the main thread which runs the WPF/Silverlight Ul. So when you run the application you should get an exception as shown in the below “invalid cross-thread access” as shown in Figure 12.48.

WPF Interview Questions in .NET chapter 12 img 43

Question 60.
So how do we make the code working?
To make threading working in WPF and Silverlight we need to use the “Dispatcher” object. So rather than making calls directly to the Ul object, we need to route the calls via dispatcher object. The dispatcher object then prioritizes and executes the calls on the thread’s behalf to the Ul control (See Figure 12.49).

WPF Interview Questions in .NET chapter 12 img 44

So to make the above code working we need to call the code from within the dispatcher object. We need to pass a delegate to the “Begininvoke” function (which is done by using a lambda expression ” ()=>”) of the “Dispatcher” object.

public void SetValue( )
       for (int i = 0; i < 10; i++)
           this.Dispatcher.Beginlnvoke(( ) => {textBoxl.Text = "Test";});

Question 61.
What is a background worker thread?
Background worker is a simple thread that runs in the background and helps us execute processes in the background. In order to use background worker class we need to provide two things:

  • The first thing we need to provide is the heavy processing method that we want to invoke in a multi-threading fashion. For instance, the below method “_bWorker_DoWork” has a heavy processing logic. This method is provided to the “DoWork” property of the “BackGroundWorker” class.
readonly BackgroundWorker _bWorker = new BackgroundWorker( );
_bWorker.DoWork += new DoWorkEventHandler(_bWorker_DoWork);
void _bWorker_DoWork(object sender, DoWorkEventArgs e)
    //Heavy processing logic
  • The second thing is you need to invoke the method ” RunWorkerAsync” so that the “_bWorker_DoWork” method will be executed in the background.
_bWorker.RunWorkerAsync( );

Question 62.
Question 6: What is the difference between a background worker and a dispatcher?
Dispatcher only queues and executes the multi-threaded request. The dispatcher does not create threads. While background worker actually spawns and executes methods in a multi-threaded manner.







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

Question 3.
How can we use .NET components in COM?
.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
' 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
Return PstrCustomerCode
End Get
Set(ByVal value As String)
PstrCustomerCode = value
End Set
End Property
Public Property CustomerName() As String Implements ICustomer.CustomerName
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:
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

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 . . . . . ")
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;
namespace CSharpCode
     partial class Form1: Form
           static extern int Sleep(long dwMilliseconds); 
           public Forml()
           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?
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?
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?
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?
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?
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?
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?
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( )
          // Do something to a database
        // Everything okay so far Commit the transaction
       // Something went wrong Abort and Rollback the Transaction.
  • 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?
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?
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?
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?