Saturday, June 9, 2012
WCF Interview Questions and Answer
WCF Interview Questions and Answers
Q1. What is
WCF?
WCF stands for
Windows Communication Foundation. It is a Software development kit for
developing services on Windows. WCF is introduced in .NET 3.0. in the
System.ServiceModel namespace. WCF is based on basic concepts of Service
oriented architecture (SOA)
Q2. What is endpoint in WCF service?
The endpoint
is an Interface which defines how a client will communicate with the service.
It consists of three main points: Address,Binding and Contract.
Q3. Explain Address,Binding and contract for a WCF Service?
Address:Address
defines where the service resides.
Binding:Binding
defines how to communicate with the service.
Contract:Contract
defines what is done by the service.
Q4. What are the various address format in WCF?
a)HTTP Address
Format:--> http://localhost:
b)TCP Address
Format:--> net.tcp://localhost:
c)MSMQ Address
Format:--> net.msmq://localhost:
Q5. What are the types of binding available in WCF?
A binding is
identified by the transport it supports and the encoding it uses. Transport may
be HTTP,TCP etc and encoding may be text,binary etc. The popular types of
binding may be as below:
a)BasicHttpBinding
b)NetTcpBinding
c)WSHttpBinding
d)NetMsmqBinding
Q6. What are the types of contract available in WCF?
The main
contracts are:
a)Service
Contract:Describes what operations the client can perform.
b)Operation
Contract : defines the method inside Interface of Service.
c)Data
Contract:Defines what data types are passed
d)Message
Contract:Defines wheather a service can interact directly with messages
Q7. What are the various ways of hosting a WCF Service?
a)IIS b)Self
Hosting c)WAS (Windows Activation Service)
Q8. WWhat is the proxy for WCF Service?
A proxy is a
class by which a service client can Interact with the service.
By the use of
proxy in the client application we are able to call the different methods
exposed by the service
Q9. How can we create Proxy for the WCF Service?
We can create
proxy using the tool svcutil.exe after creating the service.
We can use the
following command at command line.
svcutil.exe
*.wsdl *.xsd /language:C# /out:SampleProxy.cs /config:app.config
Q10.What is the difference between WCF Service and Web Service?
a)WCF Service
supports both http and tcp protocol while webservice supports only http
protocol.
b)WCF Service
is more flexible than web service.
Q11.What is DataContract and ServiceContract?Explain
Data
represented by creating DataContract which expose the
data which
will be transefered /consumend from the serive
to its
clients.
Q12.What is .NET
3.0?
In one simple equation .NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows
Presentation
Foundation + Windows Workflow Foundation + Windows Card Space.
Q13.What is WCF?
Windows
Communication Foundation (WCF) is an SDK for developing and deploying services
on Windows. WCF provides a runtime environment for services, enabling you to
expose CLR types as services, and to consume other services as CLR types.
First let us
give a short answer to this: - “WCF (Indigo was the code name for WCF) is a
unification of
.NET framework communication technologies
“.WCF is a
unification technology,
Q14.which unites the following technologies:-
• NET remoting
• MSMQ
• Web services
• COM+.
Q15.What was the code name for WCF?
The code name
of WCF was Indigo .
WCF is a
unification of .NET framework communication technologies which unites the
following technologies:-
1.Web services
2.MSMQ
3.NET remoting
4.COM+
Q16.What are the main components of WCF?
The main
components of WCF are
1. Service
class
2. Hosting
environment
3. End point
Q17.Where we can host WCF services?
Every WCF
services must be hosted somewhere. There are three ways of hosting WCF
services.
They are
1. IIS
2. Self
Hosting
3. WAS
(Windows Activation Service)
Q18.What is service and client in perspective of data communication?
A service is a
unit of functionality exposed to the world.
The client of
a service is merely the party consuming the service.
Q19.What are different elements of WCF Srevices Client configuration file?
WCF Services
client configuration file contains endpoint, address, binding and contract.
A sample
client config file looks like
Q20.What is endpoint in WCF?
Every service
must have Address that defines where the service resides, Contract that defines
what the service does and a Binding that defines how to communicate with the
service. In WCF the relationship between Address, Contract and Binding is
called Endpoint.
Q21.What are ends, contract, address, and bindings?
The above
terminologies are the core on which SOA stands. Every service must expose one
or more ends by
which the service can be available to the client. End consists of three
important things where,
what and how:-
• Contract
(What)
Contract is an
agreement between two or more parties. It defines the protocol how client
should communicate
with your service. Technically, it describes parameters and return values for a method.
• Address
(Where)
An Address
indicates where we can find this service. Address is a URL, which points to the
location of
the service.
• Binding
(How)
Bindings
determine how this end can be accessed. It determines how communications is
done.
For instance,
you expose your service, which can be accessed using SOAP over HTTP or
BINARY over
TCP. So for each of these communications medium two bindings will be created.
Below figure,
show the three main components of end. You can see the stock ticker
is the service
class, which
has an end hosted on http://www.soa.com
with HTTP and TCP binding support and using
Stock Ticker
interface type.
Q22.What is binding and how many types of bindings are there in WCF?
A binding
defines how an endpoint communicates to the world. A binding defines the
transport (such as HTTP or TCP) and the encoding being used (such as text or
binary). A binding can contain binding elements that specify details like the
security mechanisms used to secure messages, or the message pattern used by an
endpoint.
Q23.WCF supports nine types of bindings?
Basic binding
Offered by the
BasicHttpBinding class, this is designed to expose a WCF service as a legacy
ASMX web service, so that old clients can work with new services. When used by
the client, this binding enables new WCF clients to work with old ASMX
services.
This binding is used when we need to use SOAP over HTTP. This binding
can also be
configured to be used as HTTPS. It can be also configured to send data in plain
text or in optimized
form like MTOM.
TCP binding
Offered by the
NetTcpBinding class, this uses TCP for cross-machine communication on the
intranet. It supports a variety of features, including reliability,
transactions, and security, and is optimized for WCF-to-WCF communication. As a
result, it requires both the client and the service to use WCF.
This binding
sends binary-encoded SOAP, including support for reliable
message
transfer, security, and transactions, directly over TCP. The biggest
disadvantage of
NetTcpBinding
is that both server and client should be also made in .NET language.
Peer network binding
Offered by the
NetPeerTcpBinding class, this uses peer networking as a transport. The peer
network-enabled client and services all subscribe to the same grid and
broadcast messages to it.
IPC binding
Offered by the
NetNamedPipeBinding class, this uses named pipes as a transport for
same-machine communication. It is the most secure binding since it cannot
accept calls from outside the machine and it supports a variety of features
similar to the TCP binding.
Web Service (WS) binding
Offered by the
WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to
offer a variety of features such as reliability, transactions, and security
over the Internet.
It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with
it also
supports reliable message transfer, security and transaction. WS-Reliable
Messaging,
security with
WS-Security, and transactions with WS-Atomic Transaction supports reliable
message.
Federated WS binding
Offered by the
WSFederationHttpBinding class, this is a specialization of the WS binding,
offering support for federated security.
Duplex WS binding
Offered by the
WSDualHttpBinding class, this is similar to the WS binding except it also
supports bidirectional communication from the service to the client.
MSMQ binding
Offered by the
NetMsmqBinding class, this uses MSMQ for transport and is designed to offer
support for disconnected queued calls.
MSMQ integration binding
Offered by the
MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ
messages, and is designed to interoperate with legacy MSMQ clients.
This binding sends binary-encoded SOAP over MSMQ. This binding can
only be used
for WCF-to-WCF communication.
Q24.What are
the different concurreny modes available in WCF?
1. Single
2. Reentrant
3. Multiple
Q25.Are WCF
services protected from concurrent access by default?
Yes, WCF
services are protected from concurrent access by default, as the concurrency
mode of a WCF service is set to Single by default.
Q26.Explain
Single Concurrency Mode?
In a Single
concurrency mode only one request is processed by the same service instance. A
lock is acquired while a request is processed by a service instance. Other
threads, if any, are queued, until they timeout. Once the lock is released when
the current request completes, next thread in the queue can then access the
objects.
Q27.What effect does Single concurreny mode setting have on PerCall, PerSession and Singleton services?
PerCall
services and Single Concurreny mode
: A new service instance is allocated for each thread. Here, concurrency is not
an issue and Single mode setting has no impact on the throughput and concurrent
calls can be processed.
Q28.PerSession services and Single Concurreny mode : Service instances are protected against multithreaded clients. Single mode impacts throughput of single client but multiple clients can get through and concurrent calls can be processed.
Q29.Singleton services and Single Concurreny mode : Service instances are protected against any concurrent calls. Single concurrency mode impacts throughput of singleton. Multiple threads and clients cannot get through and no concurrent calls can be processed.
Q30.Explain Reentrant Concurrency Mode?
Reentrant
concurrency mode is useful when services issue callbacks
to clients, If callback operations are not one-way. Services release the
acquired lock upon exit to make the callback and another thread is able to
acquire the lock. In this case, return from callback will queue.
Q31.What effect
does Reentrant concurreny mode setting have on PerCall, PerSession and
Singleton services?
PerCall
services and Reentrant Concurreny mode
: In a case where PerCall services may need reentrancy, if we set the
concurrency mode to Single, deadlock is guaranteed, where as if it is In
Reentrant mode, we will have no problem.
Q32.PerSession services and Reentrant Concurreny mode : PerSession services allow a multithreaded client to access the service instance
Q33.Singleton services and Reentrant Concurreny mode : Singleton services allow any threads to access the service instance
Q34.What is the
effect of Multiple concurrency mode on PerSession services with multithreaded
clients?
PerSession
services with multithreaded clients can have increased throughput, with
Multiple concurrency mode, as no locks are acquired when requests are being
processed by a service instance. However, care should be taken to protect
shared resources.
Q35.What are
different .NET multithreading techniques available to protect a shared
resource?
1. Monitor
2. Mutex
3. Semaphore
4. ReadWriterLock
5. Interlocked
Q36.What are
the factors that can influence overall throughput for a service, when multiple
concurrency mode is enabled?
1. Instancing mode
2. Concurrency mode
3. Throttling behavior
Q37.What is
ServiceThrottleBehavior?
ServiceThrottleBehavior
provides several settings for throughput control, as shown below.
MaxConcurrentCalls: Maximum concurrent
requests allowed. The default is 16 .
MaxConcurrentInstances: Maximum concurrent
service instances allowed . The default is int.MaxValue.
MaxConcurrentSessions: Maximum concurrent
active sessions. This includes transport, reliable, secure, and application
sessions. The default is 10.
Hosting WCF Services in IIS
To host a WCF Service in IIS, you need a new physical file with the .svc
extension. The file associates a service with its implementation and is
the means for IIS to create ServiceHost for you. IIS takes over the interaction between your service and ServiceHost; you no longer have to instantiate and start ServiceHost yourself. The first line of the .svc file contains a directive enclosed in the ASP.NET <% Page %>
directive that tells the hosting environment to which service this file
points. The service code can then reside inline and it is a separate assembly registered in the GAC, in an assembly that
resides in the application's Bin folder, or in a C# file that resides
under the application's App_Code folder. The most common scenario is to
define endpoints in a configuration file. In IIS, you have to define
your endpoints in the Web.config file.
The most rich hosting option for WCF is IIS[ from IIS 7.0 onwords] and all hosting requirements for any good service is provided by IIS.
Step 2: I have created sample MyService service, which will display 'Hello Wolrd ' and returning "Service is running..". Interface and implementation of the Service is shown below.
write the following code under IMyService.cs
Note:
You need to mention the service file name, along with the Address mention in the config file.
IIS Screen shot
This screen will appear when we run the application.
The most rich hosting option for WCF is IIS[ from IIS 7.0 onwords] and all hosting requirements for any good service is provided by IIS.
The main advantage of hosting service in IIS is that, it will
automatically launch the host process when it gets the first client
request. It uses the features of IIS such as process recycling, idle
shutdown, process health monitoring and message based activation. The
main disadvantage of using IIS is that, it will support only HTTP
protocol.
Let as do some hands on, to create service and host in IIS
Step 1:Start the Visual Studio 2010 and click
File->New->Web Site. Select the 'WCF Service' and Location as
http. This will directly host the service in IIS and click OK.
- Remove Service.cs,IService.cs and Service.svc from our IIHostingService Project
Step 2: I have created sample MyService service, which will display 'Hello Wolrd ' and returning "Service is running..". Interface and implementation of the Service is shown below.
write the following code under IMyService.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using
System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
// NOTE: You can use
the "Rename" command on the "Refactor" menu to change the
interface name "IMyService" in both code and config file together.
[ServiceContract]
public interface IMyService
{
[OperationContract]
string
GetMessage();
}
write the following code under MyService.cs
using System;
using
System.Collections.Generic;
using System.Linq;
using
System.Runtime.Serialization;
using
System.ServiceModel;
using System.Text;
// NOTE: You can use
the "Rename" command on the "Refactor" menu to change the
class name "MyService" in code, svc and config file together.
public class MyService : IMyService
{
public void DoWork()
{
}
public string GetMessage()
{
Console.WriteLine("Hello World");
return "Service is running ";
}
}
Step 3:
Service file (.svc) contains name of the service and code behind file name. This file is used to know about the service.
MyService.svc
<%@ ServiceHost Language="C#" Debug="true" Service="MyService" CodeBehind="~/App_Code/MyService.cs" %>
Step 4:
Server side configurations are mentioned in the config file. Here I have
mention only one end point which is configured to 'wsHttpBinding', we
can also have multiple end point with differnet binding. Since we are
going to hosted in IIS. We have to use only http binding. We will come
to know more on endpoints and its configuration in later tutorial.
Web.Config
<system.serviceModel> <services> <service behaviorConfiguration="ServiceBehavior" name="MyService"> <endpoint address="http://localhost/IISHostedService/MyService.svc" binding="wsHttpBinding" contract="IMyService"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
Step 5:
Now we successfully hosted the service in IIS. Next we have to consume
this service in client application. Before creating the client
application, we need to create the proxy for the service. This proxy is
used by the client application, to interact with service.
To create the proxy, run the Visual Studio 2008 command prompt. Using
service utility we can create the proxy class and its configuration
information.
After executing this command we will find two file generated in the default location.
svcutil http://localhost/IISHostedService/MyService.svc
- MyService.cs - Proxy class for the WCF service
- Output.config - Configuration information about the service.
Step 6:
Now we will start creating the Console application using Visual Studio 2010(Client application).
Step 7:
Add the reference 'System.ServiceModel'; this is the core dll for WCF.
Step 8:
Create the object for the proxy class and call the HelloWorld method.
Step 9:
If we run the application we will find the output as shown below.static void Main(string[] args)
{
//Creating Proxy for the MyService
MyServiceClient client = new MyServiceClient();
Console.WriteLine("Client calling the service...");
Console.WriteLine(client.HelloWorld("Ram"));
Console.Read();
}
WCF Hosting
The service-host application is the
program that holds the service that has the actual objects. This is the server
if you like to call it that.
WCF Hosting are three Types:
- Self-hosting in any managed .NET application
- Hosting in a Windows service
- Hosting in different versions of IIS
Windows
Communication Foundation (WCF) Services can be hosted with Internet Information
Services (IIS); with the new Windows Activation Service (WAS) installed with
IIS 7.0; or with any managed application process including console, Windows
Forms, Windows Presentation Foundation (WPF), or managed Windows service
applications. Selecting the right hosting environment for your services is a
choice driven largely by deployment requirements related to transport protocol
and operating platform.
Hosting
Environment Features
A
.NET application requires a hosting Windows process. Inside that Windows
process, you can host multiple .NET application domains. An application domain
is the means for the .NET CLR to isolate the managed code from Windows. The CLR
automatically creates one default application domain in each worker process
where it is initialized in a process. The default application domain is not
unloaded until the process in which it runs shuts down. The CLR controls the
shutdown of the default application domain. In most hosts, no code is running
inside the default application domain. Instead, hosts (or processes)
create a new application domain so the application domain can be closed
independently of the process. In a lot of applications, it is desirable that
the client-side code and server-side code execute in different application
domains. Often, these desires stem from reasons such as security and isolation.
The
relationship between processes and application domains is similar to the
relationship between applications and application domains and the WCF ServiceHost. Bellow image illustrates, every process has at least one application domain,
and each application domain can host zero or more WCF ServiceHost
instances. WCF requires at least an application domain hosted inside a Windows
process.
To
be able to determine which host is the most applicable host for your scenario,
you should refer to your nonfunctional requirements. Typically, nonfunctional
requirements state technical requirements for your application to ensure they
meet the quality and maintainability of your application. For WCF applications,
this comes down to the following topics:
- Availability: When do you want to be able to reach your service?
- Reliability: What happens when your service somehow breaks? How does this affect other consumers?
- Manageability: Do you need easy access to information about what is happening on the host where WCF services live?
- Versioning: Do you need to support older versions of the service? Do you know who is consuming your services?
- Deployment: What is your deployment model? Are you installing through the Microsoft Installer process and Visual Studio deployment packages, or is xcopy sufficient?
- State: Are your services stateless? Do you need sessions?
Based
on these nonfunctional requirements, you can decide which host meets your
needs. To help you with this choice, for the remaining part of this chapter you
will look at the different hosting environments, including their advantages and
disadvantages.
Note The WCF programming model is agnostic to
where it is running, so switching to a different host later is always possible
and doesn't mean you have to change your service implementation. Typically, you'll
start with a self-hosted scenario in a console application to test-drive and
prototype your services.
Developing WCF Service using VS.Net Support
Microsoft VisualStudio Net provides many templates for developing as well as consuming wcf services.It has to two important/core templates for developing wcf service.These templates not only make our work easier but also they help us in developing wcf service in standard approach.
Apart from these templates we have other concepts/Projects related wcf templates also means wcf azure template...wcf cloud based service,wcf ajax template...wcf ajax based service...many more like this.
It is highly recommended to use these templates and develop the require projects instead of manually handling them.
BasicHttpBinding => SOAP+HTTPwsHttpBinding => SOAP+Security+Performance+HTTP
WCF Service Library
- A sample wcf interface and derived class.
- It provides app config file,where all service endpoints and behavior are written as follows:
<system.serviceModel>
<services>
<service name="JobService.Jobs">
<endpoint address="" binding="wsHttpBinding" contract="JobService.IJobs">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"
/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8732/Design_Time_Addresses/JobService/Jobs/" />
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing
metadata information,
set the value below to false and
remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="True"/>
<!-- To receive exception
details in faults for debugging purposes,
set the value below to true. Set to false before deployment
to avoid disclosing exception
information -->
<serviceDebug includeExceptionDetailInFaults="False" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
Devolping wcf Service Jobservice:
To develop jobservice first we have download pubs database .
- write the following code under IJobs.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
namespace JobService
{
// NOTE: You can use the "Rename" command on the
"Refactor" menu to change the interface name "IJobs" in
both code and config file together.
[ServiceContract]
public interface IJobs
{
[OperationContract]
Job GetJobInfo(int
jobid);
[OperationContract]
DataSet GetJobs();
[OperationContract]
List<Job>
GetAllJobs();
[OperationContract]
void Dowoker();
}
}
2.write the following code under Jobs.cs
using
System.Collections.Generic;
using System.Linq;
using
System.Runtime.Serialization;
using
System.ServiceModel;
using System.Text;
using
System.Data.SqlClient;
using System.Data;
namespace JobService
{
// NOTE: You can
use the "Rename" command on the "Refactor" menu to change
the class name "Jobs" in both code and config file together.
public class Jobs : IJobs
{
string
cnstr = @"Data Source=SUDHAKAR-PC;Initial
Catalog=Pubs;User ID=sa;Password=#sa#";
public void DoWork()
{
}
public Job GetJobInfo(int
jobid)
{
SqlConnection
con = new SqlConnection(cnstr);
SqlCommand
cmd = new SqlCommand("select * from jobs where job_id="+jobid,con);
Job
jobdata = new Job();
con.Open();
SqlDataReader
dr=cmd.ExecuteReader();
if
(dr.Read())
{
jobdata.Description =
dr[1].ToString();
jobdata.JobID = jobid;
jobdata.MinLevel = Convert.ToInt32(dr[2]);
jobdata.MaxLevel = Convert.ToInt32(dr[3]);
}
else
{
jobdata.JobID = -1;
}
con.Close();
return
jobdata;
}
public
System.Data.DataSet GetJobs()
{
SqlConnection
con = new SqlConnection(cnstr);
SqlDataAdapter
da = new SqlDataAdapter("select * from jobs",con);
DataSet
ds = new DataSet();
da.Fill(ds,"jobs");
return
ds;
}
public List<Job>
GetAllJobs()
{
//JobsDataDataContext
dc=new JobsDataDataContext();
//List<job>
obj = new List<job>();
//obj =
dc.jobs.ToList();
//return
obj;
throw
new NotImplementedException();
}
public void Dowoker()
{
throw
new NotImplementedException();
}
}
}
3. write the following code under Job.cs
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Text;
using
System.Runtime.Serialization;
namespace
JobService
{
[DataContract]
public class Job
{
[DataMember]
public int JobID { get; set; }
[DataMember]
public string
Description { get; set; }
[DataMember]
public int MinLevel { get; set; }
[DataMember]
public int MaxLevel { get; set; }
}
}
Subscribe to:
Posts (Atom)





