Wednesday, 31 December 2014

Tuesday, 16 December 2014

Top 10 ASP.NET MVC Interview Questions


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

MVC (Model-View-Controller) is an architectural software pattern that basically decouples various components of a web application. By using MVC pattern, we can develop applications that are more flexible to changes without affecting the other components of our application.
  •  “Model”, is basically domain data.
  •  “View”, is user interface to render domain data.
  •  “Controller”, translates user actions into appropriate operations performed on model.

2. What is ASP.NET MVC?

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

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

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

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

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

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

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

6. What is Routing in ASP.NET MVC?

In case of a typical ASP.NET application, incoming requests are mapped to physical files such as .aspx file. On the other hand, ASP.NET MVC framework uses friendly URLs that more easily describe user’s action but not mapped to physical files. Let’s see below URLs for both ASP.NET and ASP.NET MVC.
//ASP.NET  approach – Pointing to physical files (Student.aspx)
//Displaying all students
http://locahost:XXXX/Student.aspx

//Displaying a student by Id = 5

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

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

//Displaying student by Id = 5

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

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

In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options i.e. ViewData, ViewBag and TempData.
Both ViewBag and ViewData are used to to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs. So, in short, its a mechanism to maintain state between controller and corresponding view. ViewData is a dictionary object while ViewBagis a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn’t have typecasting and null checks.
TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects i.e from one controller to the other controller.ViewData Vs ViewBag Vs TempData
You can easily find detailed examples for implementation of ViewBag, ViewData and TempData here.
Back to top

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

As I already explained about request flow in ASP.NET MVC framework that request coming from client hits controller first. Actually MVC application determines the corresponding controller by using routing rules defined in Global.asax. And controllers have specific methods for each user actions. Each request coming to controller is for a specific Action Method. The following code sample, “ShowBook” is an example of an Action Method.
  public ViewResult ShowBook(int id)
  {
           var computerBook = db.Books.Where(p => P.BookID == id).First();
           return View(computerBook);
  }
Action methods perform certain operation using Model and return result back to View. As in above example,ShowBook is an action method that takes an Id as input, fetch specific book data and returns back to Viewas ViewResult. In ASP.NET MVC, we have many built-in ActionResults type:
  • ViewResult
  • PartialViewResult
  • RedirectResult
  • RedirectToRouteResult
  • ContentResult
  • JsonResult
  • EmptyResult
  • and many more….
For a complete list of available ActionResults types with Helper methods, please click here.
Important Note: All public methods of a Controller in ASP.NET MVC framework are considered to be Action Methods by default. If we want our controller to have a Non Action Method, we need to explicitly mark it withNonAction attribute as follows:
[NonAction]
public void MyNonActionMethod() { ….. }

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

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

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

If we need to apply some specific logic before or after action methods, we use action filters. We can apply these action filters to a controller or a specific controller action. Action filters are basically custom classes that provide a mean for adding pre-action or post-action behavior to controller actions.
For example,
  • Authorize filter can be used to restrict access to a specific user or a role.
  • OutputCache filter can cache the output of a controller action for a specific duration.

More Interview Questions on ASP.NET MVC

What is a ViewEngine in ASP.NET MVC?

“View Engine in ASP.NET MVC is used to translate our views to HTML and then render to browser.”
There are few View Engines available for ASP.NET MVC but commonly used View Engines are Razor, Web Forms/ASPX, NHaml and Spark etc. Most of the developers are familiar with Web Forms View Engine (ASPX) and Razor View Engine.
  • Web Form View Engine was with ASP.NET MVC since beginning.
  • Razor View Engine was introduced later in MVC3.
  • NHaml is an open source view engine since 2007.
  • Spark is also an open source since 2008.

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

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

ASPX View Engine

Razor View Engine

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

What is a ViewModel in ASP.NET MVC?

A ViewModel basically acts as a single model object for multiple domain models, facilitating to have only one optimized object for View to render. Below diagram clearly express the idea of ViewModel in ASP.NET MVC:ViewModel in ASP.NET MVC
There are multiple scenarios where using ViewModel becomes obvious choice. For example:
  • Parent-Child View Scenario
  • Reports where often aggregated data required
  • Model object having lookup data
  • Dashboards displaying data from multiple sources

What are ASP.NET MVC HtmlHelpers?

ASP.NET MVC HtmlHelpers fulfills almost the same purpose as that of ASP.NET Web From Controls. For imlementation point of view, HtmlHelper basically is a method that returns a string ( i.e. an HTML string to render HTML tags). So, in ASP.NET MVC we have HtmlHelpers for links, Images and for Html form elements etc. as follows:
@Html.ActionLink(“WebDev Consulting Company Profile”, “CompanyInfo”) will render:
<a href=”/Site/CompanyInfo”>WebDev Consulting Company Profile</a>
and
@Html.TextBox(“strEmployeeName”) renders:
<input id=”strEmployeeName” name=”strEmployeeName” type=”text” value=”” />
For a complete reference to Standard ASP.NET MVC Html Helpers, Click Here.
Note: Html Helpers are comparatively lightweight because these don’t have ViewState and event model as for ASP.NET Web Form Controls.
We can also create our Custom Html Helpers to fulfill specific application requirements. There are 2 ways to create custom HtmlHelpers as follows:Custom Html Helpers
Back to top

What is Bootstrap in MVC5?

Bootstrap (a front-end framework) is an open source collection of tools that contains HTML and CSS-based design templates along with Javascript to create a responsive design for web applications. Bootstrap provides a base collection including layouts, base CSS, JavaScript widgets, customizable components and plugins.
Project Template in ASP.NET MVC5 is now using bootstrap that enhances look and feel with easy customization. Bootstrap version 3 is added to ASP.NET MVC5 template as shown below:Bootstrap Template in MVC5
Back to top

Kindly explain Attribute Routing in ASP.NET MVC5?

We already have discussed about Routing in Question#6 that in ASP.NET MVC, we use friendly URLs that are mapped to controller’s actions instead of physical files as in case of ASP.NET WebForms. Now in ASP.NET MVC5, we can use attributes to define routes giving better control over the URIs.
We can easily define routes with Controller’s action methods as follows:Attribute Routing in MVC5
Note: Remember that conventional routing approach is not discarded, it’s still there and fully functional. Also, we can use both routing techniques in a same application. Click here for more details on Attribute Routing.

Top 10 WCF Interview Questions

WCF Interview Questions List

1. What is the difference between WCF and ASMX Web Services?

Simple and basic difference is that ASMX or ASP.NET web service is designed to send and receive messages using SOAP over HTTP only. While WCF can exchange messages using any format (SOAP is default) over any transport protocol (HTTP, TCP/IP, MSMQ, NamedPipes etc).ASMX Web Services Vs WCF
You can follow another tutorial WCF Vs ASMX for detailed discussion on this topic.
Back to Top

2. What are WCF Service Endpoints? Explain.

For Windows Communication Foundation services to be consumed, it’s necessary that it must be exposed; Clients need information about service to communicate with it. This is where service endpoints play their role. Client uses endpoint to communicate with WCF Service. A WCF service endpoint has three basic elements i.e. Address, Binding and Contract.ABC's of WCF EndPoint
  • Address: It defines “WHERE”. Address is the URL that identifies the location of the service.
  • Binding: It defines “HOW”. Binding defines how the service can be accessed.
  • Contract: It defines “WHAT”. Contract identifies what is exposed by the service.WCF Endpoint
A WCF Service can have multiple endpoints configured to accommodate different clients, for example, one client may be using HTTP while other configured to communicate over TCP.

Back to Top

3. What are the possible ways of hosting a WCF service? Explain.

For a Windows Communication Foundation service to host, we need at least a managed processa ServiceHost instance and an Endpoint configured. Possible approaches for hosting a service are:
  • Hosting in a Managed Application/ Self Hosting
    • Console Application
    • Windows Application
    • Windows Service
  • Hosting on Web Server
    • IIS 6.0 (ASP.NET Application supports only HTTP)
    • Windows Process Activation Service (WAS) i.e. IIS 7.0 supports HTTP, TCP,
      NamedPipes, MSMQ.
If you are looking for implementation of all Hosting options, please follow here (Console | Windows Service | IIS |WAS)

Back to Top

4. How we can achieve Operation Overloading while exposing WCF Services?

By default, WSDL doesn’t support operation overloading. Overloading behavior can be achieved by using “Name” property of OperationContract attribute.
 [ServiceContract]
 interface IMyCalculator
 {
        [OperationContract(Name = "SumInt")]
        int Sum(int arg1,int arg2);        [OperationContract(Name = "SumDouble")]
        double Sum(double arg1,double arg2);
  }
When the proxy will be generated for these operations, it will have 2 methods with different names i.e. SumInt and SumDouble.

Back to Top

Important Note: Remember that during a technical Interview, interviewer always ask about the latest feature of that particular technology, so be prepare for it also. For latest features series on Windows Communication Foundation v4.5, Click here.

5. What Message Exchange Patterns (MEPs) supported by WCF? Explain each of them briefly.

  1. Request/Response
  2. One Way
  3. Duplex
Request/Response
It’s the default pattern. In this pattern, a response message will always be generated to consumer when the operation is called, even with the void return type. In this scenario, response will have empty SOAP body.
One Way
In some cases, we are interested to send a message to service in order to execute certain business functionality but not interested in receiving anything back. OneWay MEP will work in such scenarios.
If we want queued message delivery, OneWay is the only available option.
Duplex
The Duplex MEP is basically a two-way message channel. In some cases, we want to send a message to service to initiate some longer-running processing and require a notification back from service in order to confirm that the requested process has been completed.WCF Request-Reply MEP
Please follow for detailed implementation for Message Exchange Patterns in WCF here.

Back to Top

6. What is DataContractSerializer and How its different from XmlSerializer?

Serialization is the process of converting an object instance to a portable and transferable format. So, whenever we are talking about web services, serialization is very important.
Windows Communication Foundation has DataContractSerializer that is new in .NET 3.0 and uses opt-in approach as compared to XmlSerializer that uses opt-out. Opt-in means specify whatever we want to serialize while Opt-out means you don’t have to specify each and every property to serialize, specify only those you don’t want to serialize.
DataContractSerializer is about 10% faster than XmlSerializer but it has almost no control over how the object will be serialized. If we wanted to have more control over how object should be serialized that XmlSerializer is a better choice.

Back to Top

7. How we can use MessageContract partially with DataContract for a service operation in WCF?

MessageContract must be used all or none. If we are using MessageContract into an operation signature, then we must use MessageContract as the only parameter type and as the return type of the operation.

Back to Top

8. Which standard binding could be used for a service that was designed to replace an existing ASMX web service?

The basicHttpBinding standard binding is designed to expose a service as if it is an ASMX/ASP.NET web service. This will enable us to support existing clients as applications are upgrade to WCF.

Back to Top

9. Please explain briefly different Instance Modes in WCF?

WCF will bind an incoming message request to a particular service instance, so the available modes are:
  • Per Call: instance created for each call, most efficient in term of memory but need to maintain session.
  • Per Session: Instance created for a complete session of a user. Session is maintained.
  • Single: Only one instance created for all clients/users and shared among all.Least efficient in terms of memory.PerCall - WCF

10. Please explain different modes of security in WCF? Or Explain the difference between Transport and Message Level Security.

In Windows Communication Foundation, we can configure to use security at different levels
a.    Transport Level security means providing security at the transport layer itself. When dealing with security at Transport level, we are concerned about integrity, privacy and authentication of message as it travels along the physical wire. It depends on the binding being used that how WCF makes it secure because most of the bindings have built-in security.
  <netTcpBinding>
         <binding name=”netTcpTransportBinding”>
                    <security mode=”Transport”>
                          <Transport clientCredentialType=”Windows” />
                    </security>
          </binding>
  </netTcpBinding>
b.    Message Level Security
For Tranport level security, we actually ensure the transport that is being used should be secured but in message level security, we actually secure the message. We encrypt the message before transporting it.
   <wsHttpBinding>
            <binding name=”wsHttpMessageBinding”>
                          <security mode=”Message”>
                                     <Message clientCredentialType=”UserName” />
                          </security>
             </binding>
     </wsHttpBinding>
It totally depends upon the requirements but we can use a mixed security mode also as follows:
      <basicHttpBinding>
             <binding name=”basicHttp”>
                          <security mode=”TransportWithMessageCredential”>
                               <Transport />
                               <Message clientCredentialType=”UserName” />
                          </security>
              </binding>
       </basicHttpBinding>

Interview Questions Answers – Windows Communication Foundation (WCF)

What is service ?

A service is a unit of functionality exposed to the world. Service orientation (SO) is an abstract set of principles and best practices for building service-oriented applications.

What do you mean by client ?

The client of a service is the program unit consuming its functionality. The client can
be literally anything—for instance, Console application, Windows Forms, WPF, or Silverlight class, anASP.NET page, or another service.

What is WCF ?

  • Stands for Windows Communication Foundation.
  • Its code name is “Indigo”.
  • It is a framework for building, configuring and deploying interoperable distributed services.
  • It enables you to write more secure flexible services without any code change (using configuration).
  • It also provide built-in support for logging. You can enable/disable logging using configuration.
WCF = Web Service + Remoting + MSMQ + COM+
or
WCF = ASMX + .Net Remoting + WSE + Messaging + Enterprise Services

What are the transport schemes supported by WCF ? Give example of address for each scheme.

Following are the transport schemes supported by WCF:
  • HTTP/HTTPS - http://localhost:8001/MyService
  • TCP - net.tcp://localhost:8002/MyService
  • IPC - net.pipe://localhost/MyPipe
  • Peer network
  • MSMQ - net.msmq://localhost/private/MyQueue
  • Service bus - sb://MyNamespace.servicebus.windows.net/

What is Contract ? What are the types of Contract ?

It is the agreement between client and service which specifies:
  • [ServiceContract] - which services are exposed to the client.
  • [OperationContract] - which operations the client can perform on the service.
  • [DataContract] – which data types are passed to and from the service.
  • [MessageContract] - allow the service to interact directly with messages. Message contracts can be typed or untyped and are useful in interoperability cases when another party has alreadydictated some explicit (typically proprietary) message format.
  • [FaultContract] -which errors are raised by the service and how the service handles andpropagates errors to its clients.

What is the difference between Web Service and WCF Service ?

FeaturesWeb ServiceWCF
HostingIt can be hosted in IIS.It can be hosted in IIS, WAS (windows activation service), Self-hosting or Windows service
ProgrammingApply [WebService] attribute to the class to be exposed as a service.Apply [ServiceContract] attribute to the class to be exposed as a service.
ModelApply [WebMethod] attribute to the method exposed to client.Apply [OperationContract] attribute to the method exposed to client.
Supported OperationsOne-way and Request- Response.One-Way, Request-Response and Duplex.
LoggingNeeds custom implementation.No custom implementation needed. Can be configured in service config file.
SerializationSystem.Xml.serialization namespace is used.System.Runtime.Serialization namespace is used.
Supported EncodingXML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom.XML 1.0, MTOM, Binary, Custom.
Supported TransportsCan be accessed through HTTP, TCP and Custom.Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P(Peer to Peer) and Custom.
Service TypesASMX, .Net Remoting.ASMX, .Net Remoting, WSE(WS* Protocols), MSMQ and Enterprise Services
Supported ProtocolsSecuritySecurity, Reliable messaging, Transactions

How can we host WCF service ?

Every WCF service needs to be hosted in a windows process called the host process. A single host process can host multiple services, and the same service type can be hosted in multiple host processes.
WCF services can be hosted in many ways:
IIS 5/6 Hosting
WCF services can be hosted in IIS. It is similar to hosting a ASMX web service. To host a WCF service, you need to create a .svc file similar to this example and put it in virtual directory of IIS:
<%@ ServiceHost Language = "C#" Debug = "true" CodeBehind = "˜/App_Code/MyService.cs" Service = "MyService" %>
Instead of defining a .svc file, you can create and host the service in .config file as below:
<system.serviceModel>
  <serviceHostingEnvironment>
    <serviceActivations>
      <add relativeAddress = "MyService.svc" service = "WcfService.MyService"/>
      <add relativeAddress = "MyOtherService.svc" service = "MyOtherService"/>
    </serviceActivations>
  </serviceHostingEnvironment>
  <services>
    <service name = "WcfService.MyService">
      ...
    </service>
    <service name = "MyOtherService">
      ...
    </service>
  </services>
</system.serviceModel>
Self Hosting
Self-hosting is the technique in which the developer is responsible for providing and
managing the lifecycle of the host process. You can host WCF service inside any Windows process, such as a Windows Forms application, a WPF application, a Console application, or a Windows NT Service.
You can also host your WCF service as in-proc. In-process (or in-proc) hosting is the hosting technique where the service resides in the same process as the client. By definition, the developer provides the host for the in-proc hosting.
var host = new ServiceHost(typeof(MyService));
host.Open();
Console.WriteLine("Press any key to stop service");
Console.ReadKey();
host.Close();
WAS (Windows Activation Service) Hosting
Microsoft provides a generalpurpose hosting engine called the Windows Activation Service (WAS). WAS is a system service available with Windows Vista, Windows Server 2008, and Windows 7 (or later). The WAS is a true general-purpose hosting engine. It can host websites (in fact, IIS 7 will host its websites in the WAS by default), but it can just as easily host your services, allowing you to use any transport, such as TCP, IPC, or MSMQ. You can install and configure the WAS separately from IIS 7. Hosting a WCF service in the WAS is designed to look just like hosting in IIS 5/6. You need to either supply an .svc file, just as with IIS 5/6, or provide the equivalent information in the config file.
Custom Hosting in IIS/WAS
When using IIS 5/6 or WAS, you have no direct access to the host. To overcome this hurdle, WCF provides a hook called a host factory. Using the Factory tag in the .svc file, you can specify a class you provide that creates the host instance.
<%@ ServiceHost Language = "C#" Debug = "true" CodeBehind = "˜/App_Code/MyService.cs" Service = "MyService" Factory = "MyServiceFactory" %>
You can also specify the host factory in the config file when not using an .svc file explicitly:
<serviceActivations>
    <add relativeAddress = "MyService.svc" service = "MyService" factory = "MyServiceFactory" />
</serviceActivations>
Note: The host factory class must derive from the ServiceHostFactory class and override the CreateServiceHost() virtual method.
Windows Server AppFabric
AppFabric is an extension to the WAS. It is geared more toward WF services, which require support for persistence and state management correlation. Windows Server AppFabric adds items for managing and monitoring the services, as well as WCF and WF configuration items, to the IIS 7 management console. Windows Server AppFabric provides a dashboard for monitoring the running instances of WCF or WF services, and is reminiscent of the MTS or COM+ Component Services Explorer of old. Windows Server AppFabric provides health monitoring and custom diagnostics, as well as some troubleshooting features for analyzing why a service call has failed.
Windows Server AppFabric also supports scripting of all the options available in the user interface. Windows Server AppFabric offers its own events collecting system service, which stores the events in a SQL Server database. You can provide Windows Server AppFabric with tracing and tracking profiles at various verbosity levels.

How do you choose the hosting for WCF internet service ?

HowToChooseHost

What are the protocols supported by WCF hosting environment ? What are their advantages and disadvantages ?

WCF support multiple ways in which you can host your WCF service.
Hosting EnvironmentSupported protocol
IIS6http, wshttps
IIS7 – WAS (Windows Process Activation Service)http,net.tcp,net.pipe,net.msmq
Windows console and form applicationhttp,net.tcp,net.pipe,net.msmq
Windows service application (formerly known as NT services)http,net.tcp,net.pipe,net.msmq
Below is the feature summary of hosting environments:
FeatureSelf-HostingIIS HostingWAS Hosting
Executable Process/ App DomainYesYesYes
ConfigurationApp.configWeb.configWeb.config
ActivationManual at startupMessage-basedMessage-based
Idle-Time ManagementNoYesYes
Health MonitoringNoYesYes
Process RecyclingNoYesYes
Management ToolsNoYesYes

What is binding ?

A binding is the set of configurations regarding the transport protocol, message encoding, communication pattern, reliability, security, transaction propagation, and interoperability.

What are the types of bindings supported by WCF ? What are their advantages and disadvantages ?

BindingFeatureSuitable ForTransportMessage encodingSecurity ModeResource ManagerTransaction Flow
BasicHttpBindingNot secure by default.Communication with WS-Basic Profile conformant Web Services like ASMX.HTTPTextNoneXX
WSHttpBindingSecure, Interoperable.Non-duplex service contracts.HTTPTextMessageDisabledWS-Atomic
WSDualHttpBindingSecure, Interoperable.Duplex service contracts or communication through SOAP intermediaries.HTTPTextMessageEnabledWS-Atomic transaction
WSFederationHttpBindingSecure, Interoperable.Supports the WS-Federation protocol, enabling organizations that are in a federation to efficiently authenticate and authorize users.HTTPTextMessageDisabledWS-Atomic transaction
NetTcpBindingSecure, Optimized.Cross-machine communication between WCF applications.TCPBinaryTransportDisabledOle transaction.
NetPeerTcpBindingSecure.Multi-machine communication.P2PBinaryTransportXX
NetNamedPipesBindingSecure, Reliable, Optimized.On-machine communication between WCF applications.Named PipesBinaryTransportXOle transaction.
NetMsmqBindingCross-machine communication between WCF applications.MSMQBinaryMessageXX
MsmqIntegrationBindingDoes not use a WCF message encoding – instead it lets you choose a pre-WCF serialization format.Cross-machine communication between a WCF application and existing MSMQ applications.MSMQPre-WCF formatTransportXX

What is Endpoint in WCF ?

or

What is ABC in WCF ?

Endpoint = Address (A) + Binding (B) + Contract (C)
Address specifies where the services is hosted.
Binding specifies how to access the hosted service. It specifies the transport, encoding, protocol etc.
Contract specifies what type of data can be sent to or received from the service.
Eg:
<endpoint name="BasicHttpGreetingService" address="http://localhost:5487/MyService/GreetingService.svc" binding="basicHttpBinding" contract="MyNamespace.MyService.IGreetingService" />

Can you explain Address in detail ?

It is the url which specifies the location of the service. Client can use this url to connect to the service and invoke the service methods.
Eg: http://localhost:5487/MyService/GreetingService.svc

Can you explain Binding in detail ?

It specifies how to access the hosted service. There are following characteristics of binding:
Transport defines the communication protocol to be used to communicate between service and client. It may be HTTP, TCP, MSMQ, NamedPipes etc. It is mandatory to define transport.
Encoding defines the technique used to encode the data before communicating it from one end to the other.
Protocol defines the configurations like reliability, security, transaction, timouts, message size etc.

What is binding configuration ?

You can customize the binding used by endpoint using config file. For example, you can enable/disable transaction for the binding used by endpoint. All you need is to configure binding element in config file similar as below:
<bindings>
  <netTcpBinding>
    <binding name = "TransactionalTCP" transactionFlow = "true" />
  </netTcpBinding>
</bindings>

What is default endpoints ?

If the service host does not define any endpoints (neither in config nor programmatically) but does provide at least one base address, WCF will by default add endpoints to the service. These are called the default endpoints. WCF will add an endpoint per base address per contract, using the base address as the endpoint’s address. WCF will infer the binding from the scheme of the base address. For HTTP, WCF will use the basic binding. Note that the default bindings will affect the default endpoints. WCF will also name the endpoint by concatenating the binding name and the contract name.

How can we enable/disable metadata publishing of our WCF service ?

You can enable enable meta data publishing for a WCF service two ways:
  • Configure metadata publishing for a service that uses default endpoints. Specify the ServiceMetadataBehavior in the configuration file but do not specify any endpoints.
<configuration>
 <system.serviceModel>
   <behaviors>
     <serviceBehaviors>
       <behavior name="CustomServiceBehavior">
         <serviceMetadata httpGetEnabled="True" />
         <serviceDebug includeExceptionDetailInFaults="False" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>
</configuration>
  • Configure metadata publishing for a service that uses explicit endpoints. Specify the ServiceMetadataBehavior in the configuration file and a mex endpoint.
<configuration>
 <system.serviceModel>
   <services>
     <service name="MyNamespace.MyService.GreetingService" behaviorConfiguration="CustomServiceBehavior">
       <endpoint address="" binding="wsHttpBinding" contract="MyNamespace.MyService.IGreetingService" />
       <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
     </service>
   </services> 
   <behaviors>
     <serviceBehaviors>
       <behavior name="CustomServiceBehavior">
         <serviceMetadata httpGetEnabled="True" />
       </behavior>
     </serviceBehaviors>
   </behaviors>
 </system.serviceModel>
</configuration>
Supported bindings for mex endpoint are mexHttpBindingmexHttpsBindingmexNamedPipeBinding andmexTcpBinding.

How can you generate proxy class and configuration file for WCF service ?

WCF provides an utility svcutil.exe which can be used to generate proxy class and configuration file. Eg:
SvcUtil http://localhost:8002/MyService/ /out:Proxy.cs /noconfig

Is there any tool provided by Microsoft for editing configuration file ?

Yes. Microsoft provides an utility “SvcConfigEditor.exe” that can edit any configuration file.

How can you test your new WCF service without writing any client application ?

Microsoft provides a tool which can be used to test any WCF service. To use this tool, open visual studio command prompt and execute the command “wcftestclient.exe“. It will open a window where you can add many WCF services and test. You can also provide values for input parameters of WCF methods.

Which bindings support reliability and message ordering ?

Binding nameSupports
reliability
Default
reliability
Supports ordered
delivery
Default Ordered
delivery
BasicHttpBindingNoN/ANoN/A
NetTcpBindingYesOffYesOn
NetNamedPipeBindingNoN/A(On)YesN/A(On)
WSHttpBindingYesOffYesOn
NetMsmqBindingNoN/ANoN/A

How can you configure reliability using .config file ?

<bindings>
  <netTcpBinding>
    <binding name = "ReliableTCP">
      <reliableSession enabled = "true"/>
    </binding>
  </netTcpBinding>
</bindings>

How can you implement operation overloading in WCF service ?

We can implement operation overloading using “Name” property of OperationContract attribute. For eg:
[ServiceContract]
interface ICalculator
{
    [OperationContract(Name = "AddInt")]
    int Add(int arg1,int arg2);
    [OperationContract(Name = "AddDouble")]
    double Add(double arg1,double arg2);
}

What is Known Types ?

By default, you can not use a subclass of a data contract class instead of its base class. You need to explicitly tell WCF about the subclass using the KnownTypeAttribute. For eg
[DataContract]
[KnownType(typeof(SubClass))]
class BaseClass
{...}

[DataContract]
class SubClass : BaseClass
{...}

What is ServiceKnownType ?

Instead of using the KnownType attribute on the base data contract, you can apply the
ServiceKnownType attribute on a specific operation on the service side. Then, only that
operation (across all supporting services) can accept the known subclass.
[OperationContract]
[ServiceKnownType(typeof(SubClass))]
void AddContact(BaseClass baseObject);

How can we create and host a WCF service in IIS ?

How to create a service contract and operation contract ? Can you give an example ?

We can create a contract using an interface by applying [ServiceContract] and [OperationContract] attributes on Interface and Methods respectively.
[ServiceContract]
public interface IGreetingService
{
    [OperationContract]
    string GreetMe(string userName);
}

public class GreetingService : IGreetingService
{
    public string GreetMe(string userName)
    {
        return string.Format("Welcome {0}", userName);
    }
}
If we do not want to create interface then we can apply the attributes on a class itself.
[ServiceContract]
public class GreetingService
{
    [OperationContract]
    public string GreetMe(string userName)
    {
        return string.Format("Welcome {0}", userName);
    }
}

Can you give an example of DataContract ?

[DataContract]
public enum Color
{
  [EnumMember]
  Red,

  [EnumMember]
  Green,

  [EnumMember]
  Blue
}
[DataContract]
public class Shape
{
  [DataMember]
  public string Name { get; set; }

  [DataMember]
  public Color FillColor { get; set; }

  [DataMember]
  public double Area { get; set; }
}

What is MessageContract ? Can you give an example ?

WCF uses SOAP messages to transfer information from client to server and vice-versa. It converts data contract to SOAP messages. SOAP message contains Envelope, Header and Body. SOAP envelope contains name, namespace, header and body element. SOAP Header contains important information which are related to communication but not directly related to message. SOAP body contains information which is used by the target.
SOAP Envelope = Name + Namespace  + Header + Body
However there are some cases when you want to have control over the SOAP messages. You can achieve this using MessageContract.
[MessageContract]
public class Shape
{
    [MessageHeader]
    public string ID;
    [MessageBodyMember]
    public string Name;
    [MessageBodyMember]
    public double Area;
}
In above example, ID will be added as header, Name and Area as body in SOAP envelope.
When you use MessageContract then you have control over the SOAP message. However some restrictions are imposed as below:
  • You can have only one parameter for a service operation if you are using MessageContract.
  • You can return either void or MessageContract type from service operation. Service operation can not return DataContract type.
  • Service operation can accept and return only MessageContract type.
Some important points about MessageContract:
  • You can mention the MessageHeader or MessageBodyMember to be signed or Encrypted using ProtectionLevel property.
  • The order of the body elements are alphabetical by default. But you can control the order, using Order property in the MessageBody attribute.

What is FaultContract ?

In most of the cases you would like to convey the details about any error which occurred at service end. By default, WCF exceptions do not reach client. However you can use FaultContract to send the exception details to client.
[DataContract()]
public class CustomError
{
  [DataMember()]
  public string ErrorCode;
  [DataMember()]
  public string Title;
  [DataMember()]
  public string ErrorDetail;
}

[ServiceContract()]
public interface IGreetingService
{
  [OperationContract()]
  [FaultContract(typeof(CustomError))]
  string Greet(string userName);
}

public class GreetingService : IGreetingService
{
  public string Greet(string userName)
  {
    if (string.IsNullOrWhiteSpace(userName))
    {
        var exception = new CustomError()
        {
            ErrorCode = "401",
            Title = "Null or empty",
            ErrorDetail = "Null or empty user name has been provided"
        };
        throw new FaultException<CustomError>(exception, "Reason : Input error");
    }
    return string.Format("Welcome {0}", userName);
  }
}

How is the service instance created ? How can you manage or control WCF service instance creation ?

Client request can be served by using single service instance for all users, one service instance for one client, or one instance for one client request. You can control this behavior by using the technique called Instance Management in WCF.
There are three instance modes supported by WCF:
  • Per-CallService instance is created for each client request. This Service instance is disposed after response is sent back to client.
  • Per-Session (default): Service instance is created for each client. Same instance is used to serve all the requests from that client for a session. When a client creates a proxy to particular service, a service instance is created at server for that client only. When session starts, context is created and when it closes, context is terminated. This dedicated service instance will be used to serve all requests from that client for a session. This service instance is disposed when the session ends.
  • Singleton: All client requests are served by the same single instance. When the service is hosted, it creates a service instance. This service instance is disposed when host shuts down.
You can configure instance mode using [ServiceBehavior] attribute as below:
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public class MyService:IGreetingService

Can you control when the service instance is recycled ?

Yes, we can control when the service instance is recycled using the ReleaseInstanceMode property of theOperationBehavior attribute. You can control the lifespan of your WCF service. You can set the value ofReleaseInstanceMode property as one of the following:
  • RealeaseInstanceMode.None: No recycling behavior.
  • RealeaseInstanceMode.BeforeCall: Recycle a service object before an operation is called.
  • RealeaseInstanceMode.AfterCall: Recycle a service object after an operation is called.
  • RealeaseInstanceMode.BeforeAndAfterCall: Recycle a service object both before and after an operation is called.

Can you limit how many instances or sessions are created at the application level ?

Yes, you can limit how many instances or sessions are created at the application level. For this, you need to configure throttling behavior for the service in its configuration file. Some of these important properties are:
  • maxConcurrentCalls limits the total number of calls that can currently be in progress across all service instances. The default is 16.
  • maxConcurrentInstances limits the number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue.
  • maxConcurrentSessions limits the number of sessions a ServiceHost object can accept. It is a positive integer that is 10 by default.
<behaviors>
 <serviceBehaviors>
   <behavior name="ServiceBehavior">
     <serviceThrottling maxConcurrentCalls="500" maxConcurrentInstances ="100" maxConcurrentSessions ="200"/>
   </behavior>
 </serviceBehaviors>
</behaviors>

What are session modes in WCF ? How can you make a service as sessionful ?

ServiceContract attribute offers the property SessionMode which is used to specify the session mode. There are three session modes supported by WCF:
  • Session.Allowed(default): Transport sessions are allowed, but not enforced. Service will behave as a per-session service only if the binding used maintains a transport-level session.
  • Session.Required: Mandates the use of a transport-level session, but not necessarily an application-level session.
  • Session.NotAllowed: Disallows the use of a transport-level session, which precludes an application-level session. Regardless of the service configuration, the service will always behave as a per-call service.
[ServiceContract(SessionMode = SessionMode.NotAllowed)]
interface IMyContract
{...}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract
{...}

What is the instance mode as a product of the binding, contract configuration, and service behavior ?

BindingSession modeContext modeInstance mode
BasicAllowed/
NotAllowed
PerCall/
PerSession
PerCall
TCP, IPCAllowed/
Required
PerCallPerCall
TCP, IPCAllowed/
Required
PerSessionPerSession
WS
(no Message security, no reliability)
NotAllowed/
Allowed
PerCall/
PerSession
PerCall
WS
(with Message security or reliability)
Allowed/
Required
PerSessionPerSession
WS
(with Message security or reliability)
NotAllowedPerCall/
PerSession
PerCall

What is MEP (Message Exception Pattern) in WCF ?

MEP describes the way in which Client and Server communicates. It describes how client and server would be exchanging messages to each other. There are three types of message exchange patterns:
  • Request- Replay (default): When client makes a request to the WCF service, it waits to get response from service till receiveTimeout expires. If client does not get any response from the service before receiveTimeout expires, TimeoutException is thrown.
  • One-Way: When client makes a request to the WCF service, it does not wait for reply from the service. Service does not send any response to the sender, even if any error occurs in the communication. It does not support out or ref parameters. It does not return value to an operation.
  • Duplex/Callback: Client and service can sends messages to each other by using One-way or request-reply messaging. This MEP is supported by only bidirectional-capable bindings like as WS Dual, TCP and IPC bindings.To make a duplex contract, you must also define a callback contract and assign the typeof that callback contract to the CallbackContract property of your service contract’s ServiceContract attribute.
public interface IMyDuplexServiceCallback
{
[OperationContract(IsOneWay = true)]
void Progress(string status);
}

[ServiceContract(CallbackContract = typeof(IMyDuplexServiceCallback))]
public interface IMyDuplexService
{
[OperationContract(IsOneWay = true)] //One-Way
void SaveData();

[OperationContract] //Request-Reply.
string GetData();
}
For Duplex MEP, you need to specify the one of the binding which supports bi-directional like wsDualHttpBinding as in below example:
<services>
  <service name="MyWCFServices.DuplexService">
    <endpoint address ="" binding="wsDualHttpBinding" con-tract="MyWCFServices.IDuplexService">
    </endpoint>
  </service>
</services>
You can configure MEP using IsOneWay property of OperationContract attribute as below:
[OperationContract(IsOneWay = true)]

What is transaction and committed transaction in WCF ?

A transaction is a collection or group of one or more units of operation executed as a whole. It provides way to logically group multiple pieces of single work and execute them as a single unit. In addition, WCF allows client applications to create transactions and to propagate transactions across service boundaries.
A transaction that executes successfully and manages to transfer the system from the consistent state A to the consistent state B is called a committed transaction.

What is Two-phase commit protocol in WCF ? Why is it needed ?

Consider for example client calling multiple service or service itself calling another service, this type of system are called as Distributed Service-oriented application. Now the questions arise that which service will begin the transaction? Which service will take responsibility of committing the transaction? How would one service know what the rest of the service feels about the transaction? Service could also be deployed in different machine and site. Any network failure or machine crash also increases the complexity for managing the transaction. This problem is resolved by using two phase protocol.
All the transactions in WCF complete using two phase commit protocol. It is the protocol which enables transactions in a distributed environment. This protocol mainly consist of two phases:
  • Prepare phase: In this phase the client application performs the operations of a WCF service. WCF service determines whether the requested operation will be successful or not and notify the client about the same.
  • Commit Phase: In the commit phase the client checks for the responses it got from the prepare phase and if all the responses are indicating that the operation can be carried out successfully the transaction is committed. If the response from any one of the operations indicates failure then the transaction will be rolled back. The actual operation on the service end will happen in the commit phase.
WCF service will have to send the notification of whether the operation will succeed or fail to the client application. It means that the One way operations can never support transactions. The operations that support transactions have to follow the Request-Response MEP. Also the applied binding should support WS-Atomic Transaction protocol like wsHttpBinding.

What is Transaction Propagation in WCF ? Explain with example.

Suppose that there are two services CreditService and DebitService. CreditService has operation Credit(int accountId, double amount) and DebitService has operation Debit(int accountId, double amount). If you want to transfer amount from one account to another account, you need to call both the services. You also need to ensure that both the services should either succeed or fail together. You can achieve this by propagating the transaction of first service call to the second service call. Transaction Propagation is supported by WCF. You can propagate transaction across the service boundaries. It enables multiple services to participate in same transaction.
You can enable/disable transaction propagation using configuration as below:
<bindings>
   <netTcpBinding>
     <binding transactionFlow="true"></binding>
   </netTcpBinding>
</bindings>
Above configuration ensures that transaction can be propagated. However it does not force the transaction propagation until you specify for particular operation. You need to enable transaction flow for the operations whom you want to be part of transaction as below:
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Credit(int accountId, double amount);
[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Debit(int accountId, double amount);
Note: You can have single operation as which can do credit and debit. However I have separated as two for illustrating about transaction.
transactionFlow and TransactionFlowOption together enables the transaction flow for particular operation. If you enable only one of these two, transaction flow can not be enabled.
There are 3 possible values for TransactionFlowOption:
  • TransactionFlowOption.Mandatory: specifies that this function can only be called within a transaction.
  • TransactionFlowOption.Allowed: specifies that this operation can be called within a transaction but its not mandatory.
  • TransactionFlowOption.NotAllowed: specifies that this operation can not be called within a transaction.

How to create WCF transaction ?

There are some steps you need to follow to enable transaction for a WCF service as below:
Step 1: Decorate the operation contract with TransactionFlow attribute for enabling the transaction.
<code>[OperationContract]
[TransactionFlow(TransactionFlowOption.Allowed)]
bool Debit(int accountId, double amount);
Step 2: Create the service class which implements the service contract and set the operation behavior withTransactionScopeRequired = true. This attribute is used to enable the service transaction when the client transaction is not available.
<code>[OperationBehavior(TransactionScopeRequired = true)]
public bool Debit(int accountId, double amount)
{
  // Debit logic goes here
}
Step 3: Enable transaction flow in configuration file.
<bindings>
      <wsHttpBinding>
        <binding name="myTransactionBinding" transactionFlow="true" ></binding>
      </wsHttpBinding>
    </bindings>

What is Restful service ?

  • REST stands for Representational State Transfer.
  • REST is an architectural style for building distributed applications. It involves building Resource Oriented Architecture (ROA) by definding resources that implement uniform interfaces using standard HTTP verbs (GET, POST, PUT, and DELETE), and that can be located/identified by a Uniform Resource Identifier (URI).
Any Service which follows the REST architecture style is called as RESTful service.
Characteristics of RESTful services:
  • We can load the server information using web url in the browser.
  • We can access/modify the server resource using Url.
  • It allows the client, written in different language, to access or modify the resource in the server using URL.
  • It uses the http protocol for its communication and it is stateless.
  • It can transfer the data in XML,JSON,RSS,ATOM.

How can you control if and when concurrent calls are allowed ?
Or
What is concurrency modes in WCF ? Why do we use it ?

We can use Concurrency Modes in WCF to control if concurrent calls to the context are allowed or not and if yes then when concurrent calls to the instance/context should be allowed.
There are three possible values for Concurrency Modes:
ConcurrencyMode.Single(default)- only one caller at a time is allowed.
WCF will provide automatic synchronization to the service context and disallow concurrent calls by associating the context containing the service instance with a synchronization lock. If there are multiple concurrent callers to the same context while the lock is locked, all the callers are placed in a queue. Once the context is unlocked waiting callers are allowed to lock the context in the order of queue. If a call times out while blocked, WCF will remove the caller from the queue and the client will get a TimeoutException.
ConcurrencyMode.Multiple - multiple callers at a time are allowed.
WCF will not synchronize access to the service context. It means that the service context is not associated with any synchronization lock. In this case, you must manually synchronize access to the service instance state using .NET locks such as Monitor or a WaitHandle-derived class.
ConcurrencyMode.Reentrant - multiple callers at a time are allowed only if it is reentrant.
WCF associates the service context with a synchronization lock, so concurrent calls on the same instance are never allowed. However, if the reentrant service calls another service or a callback, and that call chain somehow winds its way back to the service instance that call is allowed to reenter the service instance. For example, suppose there are three services A, B and C. Service A calls service B, service B calls service C, and service C calls service A then service C is allowed to call service A because it is reentrant service.
You can set the concurrency mode for the service by setting the ConcurrencyMode property of ServiceBehavior attribute.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]