Remoting, Web Services and WCF – DOT NET Chapter Wise Interview Questions
Question 1:
What are Web services, remoting and WCF?
Answer:
When you want to communicate with remote application you will use one of them.
So when both the applications are of .NET technologies remoting is used or else you will use Web services or WCF.
Question 2:
What is an application domain?
Answer:
Application domain is a logical isolation inside a process. This logical isolation has its own memory and own boundary. Any process which runs inside this logical isolation if crashed will not affect other processes running in other application domain as shown in Figure 11.1.
Application domain helps to isolate process for better application stability.
Question 3:
What is .NET Remoting?
Answer:
.NET remoting helps to make remote object calls, which exist in different Application Domains or different machine or different geographical boundary.
When client wants to make method call on the remote object it uses proxy for it. These method calls are called as “Messages”. Messages are serialized using “formatter” class and sent to client “Channel” as shown in Figure 11.2. Client Channel communicates with Server Channel. Server Channel uses as formatter to deserialize the message and sends to the remote object.
Question 4:
Which class does the remote object has to inherit?
Answer:
All remote objects should inherit from System. MarshalbyRefObject.
Question 5:
What are two different types of remote object creation mode in .NET remoting?
Answer:
There are two different ways in which object can be created using Remoting:
- SAO (Server Activated Objects) also called as well-known call mode.
- CAO (Client Activated Objects)
SAO has two modes “Single Call” and “Singleton”. With Single Call object, the object is created with every method call thus making the object stateless. With Singleton, the object is created only once and the object is shared with all clients.
CAO are stateful as compared to SAO. In CAO, the creation request is sent from client side. Client holds a proxy to the server object created on server.
Question 6:
What are the basic steps to implement remoting?
Answer:
Enabling remoting is a four-step process:
- Create the interface which will act a proxy between server and client.
public interface Mylnterface { string SayHello(string strName); }
- Implement the interface and inherit the class from ‘MarshalByRefObject’.
public class ClsHello: MarshalByRefObject, Mylnterface { public string SayHello(string strName) { return "Hello from Remoting " + strName; } }
- Create the server and host the object on a specific channel and formatter. In the below code snippet we have hosted ‘cisHello’ on HTTP channel and binary formatter.
static void Main(string[ ] args) { HTTPChannel objHTTPChannel = new HTTPChannel(1234); Console.WriteLine("Channel initialized"); ChannelServices.RegisterChannel(objHTTPChannel, false); Console.WriteLine("Channel Registered"); RemotingConfiguration.RegisterWellKnownServiceType (typeof(ClsHello), "MySite", WellKnownObjectMode.Singleton); Console.WriteLine("Remoting Service Activated"); Console.ReadLine(); }
- Create a client who can call the object via an interface and start making method calls.
static void Main(string[] args) { HTTPChannel objChannel = new HTTPChannel(); ChannelServices.RegisterChannel(objChannel, false); Mylnterface iobj = (Mylnterface) Activator.GetObject(typeof(Mylnterface), "HTTP: //localhost: 1234/MySite"); Console.WriteLine(iobj.SayHello("Shiv")); Console.ReadLine(); }
Question 7:
What are drawbacks of remoting and how can we overcome the same?
Answer:
The biggest drawback of remoting is that at both the ends, i.e., client and server it should be .NET. In other words clients which are not .NET like Java cannot call the server methods and functions.
It can be overcomed by using Web services.
Question 8:
What is a Web Service?
Answer:
Web Services are business logic components, which provide functionality via the Internet using standard protocols, such as HTTP.
Web Services uses Simple Object Access Protocol (SOAP) in order to expose the business functionality.
SOAP defines a standardized format in XML, which can be exchanged between two entities over standard protocols such as HTTP. SOAP is platform independent so the consumer of a Web Service is therefore completely shielded from any implementation details about the platform exposing the Web Service. For the consumer it is simply a black box of send and receives XML over HTTP. So any Web service hosted on windows can also be consumed by UNIX and Linux platform.
Question 9:
What’s the difference between Web services and remoting?
Answer:
Remoting works only when both the ends, i.e., server and client are in .NET technologies. Web services are useful when the client is not .NET like Java, etc.
Question 10:
What is UDDI?
Answer:
Full form of UDDI is Universal Description, Discovery, and Integration. It is a directory which helps to publish and discover Web services.
Question 11:
What is DISCO?
Answer:
It is a Microsoft technology for publishing/discovering Web service. DISCO can define a document format along with an interrogation algorithm, making it possible to discover the Web’Services exposed on a server. DISCO makes it possible to discover the capabilities of each Web Service (via documentation) and how to interact with it. To publish a deployed Web Service using DISCO, you simply need to create a .disco file and place it in the root along with the other service-related configuration.
Question 12:
What is WSDL?
Answer:
Web Service Description Language (WSDL) is a W3C (World Wide Web Consortium) specification which defines XML grammar for describing Web Services.XML grammar describes details, such as:
- Where we can find the Web Service (its URI or Universal Resource Identifier)?
- What are the methods and properties that service supports?
- Data type support.
- Supported protocols
In short, it is a Bible of what the Web service can do. Clients can consume this WSDL and build proxy objects that clients use to communicate with the Web Services. Full WSDL specification is available at HTTP: //www.w3.org/TR/wsdl
Question 13:
What are the steps to create a Web service and consume it?
Answer:
- Create a new project by selecting the template “ASP.NET Web Service Application”.
- Expose the function which needs to be consumed by clients using ‘WebMethod’
[WebMethod] public string HelloWorld() { return "Hello World"; }
- Create a client like Windows application, right click on the client and add Web reference. This creates a simple proxy at the client-side.
- Create the object of the proxy and invoke the function and methods of the Web service.
Question 14:
How do we secure a Web service?
Answer:
Web services follows the same ASP.NET authentication methodologies, i.e., windows, forms and passport.
In the Web service Web.config file you can specify the authentication methodology and provide the credentials from the client using the below code snippet.
ServiceReferencel.ServicelSoapClient obj = new ServiceReferencel.ServicelSoapClient(); obj.ClientCredentials.UserName.UserName = "shiv"; obj.ClientCredentials.UserName.Password = "shiv@123";
Question 15:
Does Web service have state?
Answer:
You can use session variables to maintain state in Web service.
Question 16:
What is SOA?
Answer:
SOA is an architectural style for building business applications using loosely coupled services which communicate using standard messages like XML.
Question 17:
What are WS-* specification?
Answer:
In order to standardize SOA Microsoft, IBM, SUN and many other big companies came together and laid down specification called as WS-* which will bring SOA to a common platform.
Some of the below specifications are defined below:
- Messaging (WS-Addressing): SOAP is the fundamental protocol for Web services. WS Addressing defines some extra additions to SOAP headers, which makes SOAP free from underlying transport protocol. One of the good things about Message transmission is MTOM, also termed as Message Transmission Optimization Mechanism. They optimize transmission format for SOAP messages in XML-Binary formant using XML Optimized Packaging (XOP). Because the data will sent in binary and optimized format, it will give us huge performance gain.
- Security (WS-Security, WS-Trust, and WS-Secure Conversation): All the three WS-define authentication, security, data integrity and privacy features for a service.
- Reliability (WS-Reliable Messaging): This specification ensures end-to-end communication when we want SOAP messages to be traversed back and forth many times.
- Transactions (WS-Coordination and WS-Atomic Transaction): These two specifications enable transaction with SOAP messages.
- Metadata (WS-Policy and WS-Metadata exchange): WSDL is a implementation of WS- Metadata Exchange protocol. WS-Policy defines more dynamic features of a service, which cannot be expressed by WSDL.
Question 18:
How does Microsoft implement SOA and the above WS-* specifications?
Answer:
By WCF, Windows communication foundation.
Question 19:
What is WCF?
Answer:
WCF helps to implement SOA and WS-* specification. WCF is a combination of:
- NET remoting
- MSMQ (Microsoft Message Queue)
- Web services
- COM+.
Question 20:
What’s the difference between WCF and Web services?
Answer:
- WCF services can be hosted in multiple protocols like HTTP, TCP, etc. Web services can only be hosted on HTTP protocol.
- WCF has COM+ so you can call two different WCF services in a transaction, we cannot call two different Web services in one transaction.
- WCF integrates with MSMQ, for Web services we will need to write code.
In simple words below equation shows the difference with simple equation.
WCF = Web services + Remoting + MSMQ + COM+ Web service = WCF - (Remoting + MSMQ + COM+)
Question 21:
What are end point, contract, address, and bindings?
Answer:
When we want to host any WCF service we need to provide where to host it, how td host it and what
to host.
- 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.
- End point: It is the combination of contract, address and binding.
In WCF Web.config file we can specify end point, address, binding and contract as shown in the below code snippet.
<endpoint address=”HTTP: //www. questpond.com” binding=”wsHTTPBinding” contract=”WcfService3.1 Service 1 ">
Note: You can also remember end point by ABC where A stands for Address, B for Bindings and C for Contract.
Question 22:
What are the main components of WCF?
Answer:
We need to define three main components in WCF:
- Service class
- Hosting environment
- End point
Question 23:
What is a service contract, operation contract and data contract?
Answer:
Other than address, binding and contract we also need to specify the service name, function/methods of the service and data types exposed by the service.
Service contract defines the service name, while operation contract defines functions/methods associated with the service. Below is a simple sample of service contract and operation contract.
[ServiceContract] public interface InvoiceService { [OperationContract] bool Pay(Invoice Obj); }
Data Contract defines complex data types. Simple data types like int, Boolean, etc., can be recognized but for custom class data types like customer, supplier, etc., we need to define them by using data contract. Below is a simple sample of a custom data type invoice class.
[DataContract] public class Invoice { string _InvNumber = true; DateTime _InvDate ; [DataMember] public stringlnvNumber { get { return _InvNumber; } set { _InvNumber = value; } } [DataMember] public DateTimelnvDate { get { return _InvDate; } set { _InvDate = value; } } }
Question 24:
What are the various ways of hosting a WCF service?
Answer:
There are three major ways to host a WCF service:
- Self hosting: In this user hosts the WCF service in his/her own app domain.
- II hosting: In this the WCF service is hosted on IIS (Internet Information Service) server.
- WAS: You can also host WCF service on a special server software called as WAS (Windows Activation Server).
Question 25:
How do we host a WCF service in IIS?
Answer:
In order to host a WCF service in IIS we need to create a .SVC file and the .SVC file will have the behind code of the WCF service.
By default when you create a WCF service the SVC file is created which the IIS reads to understand how to run the WCF service in IIS.
IIS hosting | Self hosting |
As WCF service is hosted inside the shell of IIS we get all benefits of IIS like process recycling, automatic activation, security feature of IIS etc.
IIS only works for HTTP protocol. |
In self hosting we need to take care of all these things ourselves. That means lot of coding.
We can use any protocol for self hosting. |
In other words if its HTTP IIS is the best hoster, if its other protocols self hosting is the only option left. |
Automatic activation
IIS provides automatic activation that means the service is not necessary to be running in advance. When any message is received by the service it then launches and fulfils the request. But in case of self hosting the service should always be running.
Process recycling
If IIS finds that a service is not healthy that means if it has memory leaks etc, IIS recycles the process. Ok let us try to understand what is recycling in IIS process. For every browser instance, a worker process is spawned and the request is serviced. When the browser disconnects the worker, process stops and you loose all information. IIS also restarts the worker process. By default, the worker process is recycled at around 120 minutes. So why does IIS recycle. By restarting the worker process it ensures any bad code or memory leak do not cause issue to the whole system.
Question 26:
What are different bindings supported by WCF?
Answer:
WCF includes predefined bindings. They cover most of bindings widely needed in day-to-day application.
- BasicHTTPBinding: It is simple SOAP over HTTP with not encryption.
- wsHTTPBinding: It is same like BasicHTTPBinding but encrypted.
- NetTcpBinding: This binding sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP.
- NetNamedPipesBinding: This binding Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows- based machine.
Note: An Inter-process control (IPC) protocol is used for exchanging information between two applications, possibly running on different computers in a network. The difference between Named pipes and TCP is that named pipes have good performance in terms of communication with in processes. But when it comes to communicate across network TCP holds the best choice. So if you are using WCF to communicate with process it’s the best choice to use in terms for performance. Named pipes do not perform when the traffic is heavy as compared to TCPIP.
- NetMsmqBinding: This binding sends binary-encoded SOAP over MSMQ. This binding can only be used for WCF-to-WCF communication.
Question 27:
What is the difference between BasicHTTPBinding and WsHTTPBinding?
Answer:
BasicHTTPBinding is plain SOAP message while wsHTTPBiding is encrypted SOAP message.
WsHTTPBingding = BasicHTTPBinding + Encryption
Question 28:
Can we overload WCF service methods and functions?
Answer:
You can overload on the server side but at the client side they have to be referred by different names. You can see in the below code snippet add is an overloaded method but the client will identify them with different names i.e. ‘ Addintegers’ and ‘AddDouble’.
[ServiceCon.tr act] interface ICalculator { [OperationContract(Name="AddIntegers")] int Add(int a, int b) [OperationContract(Name="AddDouble")] double Add(double a, double b) }
Question 29:
What is a one-way operation?
Answer:
Many times we have WCF service methods and function that have long running routine. We would like WCF client to make call to these function asynchronously. In other words the WCF client calls the functions and goes ahead doing their work and the WCF service completed its work at his own leisure.
This is achieved by marking isOneWay=true on the operation contract as shown in the below code snippet.
When you mark is One Way as true the function should not return anything. In one-way operation the WCF service does not intimate the client when done. It is like fire and forget.
[ServiceContract] public interface IServicel { [OperationContract(IsOneWay=true)] void CallMe(); }
In the implementation we have made a sleep of 15 seconds.
public class Servicel: IServicel { public void CallMe() { Thread.Sleep(15000); } }
Question 30:
In one way contract we do not get call back, how can we solve the same?
Answer:
By using duplex contract.
In duplex contracts when client initiates an operation the server service provides a reference call back URI (Universal Resource Identifier) back to the client. So the client initiates a call using the proxy class and when server finishes its work it notifies the client using the callback channel. This is called as duplex messaging in WCF. If you remember in the previous question, we had no way to know when the server finished its task.
Question 31:
How can we host a service on two different protocols on a single server?
Answer:
You can host WCF service in two different bindings by providing two different end points as shown in the below code snippet.
<endpoint address="" binding="wsHTTPBinding" contract="Wcf Service3 . IServicel" /> <endpoint address="" binding="BasicHTTPBinding" contract="WcfService3.IServicel"/>
Question 32:
How can we integrate with WCF services with MSMQ?
Answer:
By hosting your “NetMsMqBinding”.
Question 33:
How can we do security in WCF services?
Answer:
There are two ways of doing WCF security Transport security and message security.
Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocolslike TCP, HTTP, MSMQ, etc., and every of these protocols have their own security mechanisms. One of the common implementation of transport level securities is HTTPS (HyperText Transfer Protocol Secure). HTTPS is implemented over HTTP protocols with SSL (Source Socket Layer) providing the security mechanism. No coding change is required it’s more of using the existing security mechanism provided by the protocol.
Message level security is implemented with message data itself. Due to this it is independent of the protocol. Some of the common ways of implementing message level security is by encrypting data using some standard encryption algorithm.
Question 34:
In what scenarios will you use message security and transport security?
Answer:
Transport | Message | |
Scenarios when we should be using one of them | When there are no intermediate systems in between this is the best methodology. If it is an intranet type of solution this is most recommended methodology. |
When there are intermediate systems like one more WCF service through which message is routed then message security is the way to go. |
Advantages | •Does not need any extra coding as protocol inherent security is used.•Performance is better as we can use hardware accelerators to enhance performance. • There is lot of interoperability support and communicating clients do not need to under stand WS security as it is built in the protocol itself. |
• Provides end to end security as it’s not dependent on protocol. Any intermediate hop in network does not affect the application.
• Supports a wide set of security options as it is not dependent on protocol. We can also implement custom security. • Needs application refactoring to implement security. |
Disadvantages | • As it’s a protocol implemented security so it works only point to point.
•As security is dependent on protocol it has limited security support and is bounded to the |
• As every message is encrypted and signed there are performance issues.
•Does not support interoperability with old ASMX (Active Server Methods (Microsoft file name |
Question 35:
Where do we specify security option in WCF services?
Answer:
There is a security tag in the Web.config file where we can specify if we want to use transport security or message security. Below is a simple code snippet for the same.
<bindings> <wsHTTPBinding> <binding name="TransportSecurity"> <security mode="Transport"> <transport clientCredentialType="None"/> </security> </binding> </wsHTTPBinding> </bindings>
Question 36:
What are the different ways of doing WCF concurrency?
Answer:
There are three ways of configuring WCF concurrency.
- Single: A single request has access to the WCF service object at a given moment of time. So only one request will be processed at any given moment of time. The other requests have to wait until the request processed by the WCF service is not completed.
- Multiple: In this scenario multiple requests can be handled by the WCF service object at any given
moment of time. In other words request are processed at the same time by spawning multiple threads on the WCF server object.
So you have great a throughput here but you need to ensure concurrency issues related to WCF server objects.
- Reentrant: A single request thread has access to the WCF service object, but the thread can exit the WCF service to call another WCF service or can also call WCF client through callback and reenter without deadlock.
WCF concurrency is configured by using concurrency mode attribute as shown in the Figure 11.3.
Question 37:
What are different ways of doing WCF instancing?
Answer:
- Per Call: New instance of WCF service are created for every call made by client.
- Per session: One instance of WCF service is created for a session.
- Single instance: Only one instance of WCF service is created for all clients.
To configure WCF instancing we need to use the instancecontextmode attribute on the service as shown below.
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Percall)] public class Service: IService { }
Question 38:
What is REST?
Answer:
REST stands for REpresentational State Transfer. REST is an architectural style where our services can communicate using simple HTTP GET, POST methods rather than using complicated SOAP format.
Question 39:
How can we make WCF rest enabled?
Answer:
To enable a WCF service with REST principles we need to specify the binding as ‘WebHttpBinding’ in our end point.
<endpoint address=”” binding=”WebHTTPBinding” contract=”IService” behaviorConfiguration=”WebBehavior1">
We also neet to specify which HTTP method will invoke the function i.e. GET or POST by using the ‘Webinvoke’ attribute as shown in the below code snippet.
[OperationContract] [Webinvoke(Method = "GET", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "GetData/{value}")] string GetData(string value
Question 40:
Can we call two WCF services in one transaction?
Answer:
Yes we can call two WCF services in one transaction using the transaction flow attribute. So if you have two WCF services called in one transaction either both of the commit or none of the commit.
In order to enable transaction in WCF service we need to use the transaction flow attribute as shown in the below code snippet.
[ServiceContract] public interface IServicel { [OperationContract] [TransactionFlow(TransactionFlowOption.Allowed)] void UpdateData(); }
You also need to define transaction flow as true for wsHttpBinding and this binding you need to specify in the end point.
<bindings> <wsHTTPBinding> <binding name="TransactionalBind" transactionFlow="true"/> </wsHTTPBinding> </bindings> <endpoint address="" binding="wsHTTPBinding" bindingConfiguration="TransactionalBind" contract="WcfServicel.IServicel”>
Finally you can call both the WCF services in one transaction using the transaction scope object as shown in the below code snippet.
using (TransactionScope ts = new Transactionscope(TransactionScopeOption.RequiresNew)) { try { ServiceReferencel.ServicelClient obj = new ServiceRef erencel. ServicelClient () ; obj.UpdateData(); ServiceReference2.ServicelClient obj1 = new ServiceReference2.ServicelClient(); obj1.UpdateData(); ts.Complete(); } catch (Exception ex) { ts.Dispose(); } }
Question 41:
How can we enable debugging and tracing on WCF services?
Answer:
WCF has readymade trace objects as shown in the below table.
Assembly Name | Description |
System.ServiceModel | Logs the following:
• Message process • Reading of configuration information • Transport-level action • Security requests |
System.ServiceModel.MessageLogging | Generates tracing information for every message that flows through the system. |
System.ServiceModel.IdentityModel | Generate trace data for authentication and authorization. |
System.ServiceModel.Activation | Emits information regarding activation of the service. |
System.Runtime.Serialization | Emits information when objects are serialized or deserialized. WCF always serializes and deserializes information during request so it’s a good event to see the content of the request. |
System.IO.Log | Emits messages with respect to Common Log File System (CLFS). |
CardSpace | Emits trace messages related to any CardSpace identity processing that occurs within WCF context. |
We can then enable tracing using the <system. diagnostio tag as shown in the below code snippet. Depending on your needs you can make an entry of the trace objects in the Web.config file.
<system.diagnostics> <sources> <source name= * System.ServiceModel" switchValue="Information, ActivityTracing"> <listeners> <add name="log" type="System.Diagnostics.XmlWriterTraceListener" initializeData="c : \Traces . svclog" /> </listeners> </source> </sources> </system.diagnostics>
Now if you run the WCF service you can see a XML file created as shown below.
#<E2ETraceEvent xmlns="HTTP: //schemas.microsoft.com/2004/06/E2ETraceEvent"> <System xmlns = "HTTP: //schemas.microsoft.com/2 004/06/windows/eventlog/ system"> <EventID>0</EventID> <Type>3</Type> <SubType Name="Transfer">0</SubType> <Level>255</Level> <TimeCreated SystemTime="2009-04-30T03: 21: 09.5625000Z" /> <Source Name="System.ServiceModel" /> <Correlation ActivityID="{00000000-0000-0000-0000-000000000000}" RelatedActivityID="{dll829b7 d2db-46d5-a4ac-49a37a56376e}" /> <Execution ProcessName="WebDev.Webserver" ProcessID="2660" ThreadID="8" / > <Channel/> <Computer>COMPAQ-JZP3 7MD0</Computer> </System> <ApplicationDatax/ApplicationData> </E2ETraceEvent>
Question 42:
How are exceptions thrown in WCF?
Answer:
If you want to inform the WCF client that there is error we need to throw a “FaultException” as shown in the below code snippet.
throw new FaultException(Error. Message. ToStringQ);
Note: A cross question after this question can be, why can’t we raise a normal .NET exception. In other words he will try to compare normal exception with fault exception. The next question answers the same in detail.
Question 43:
What is the difference between WCF fault exceptions and .NET exceptions?
Answer:
If you throw a normal .NET exception from a WCF service as shown in the below code snippet. throw new Exception(“Divide by zero”);
Your WCF client will get a very generic error with a message as shown in the Figure 11.4. Now this kind of message can be very confusing as it does not pinpoint what exactly the error is.
If you use a raise a fault exception as shown in the below code, your WCF clients will see the complete clear error rather than a generic error as shown previously.
throw new FaultException(“Divide by zero”);
Your WCF client will now see a better error description as shown in Figure 11.5.
Question 44:
What is the difference between Service endpoint and Client endpoint?
Answer:
Endpoint in WCF service is the combination of three things address, binding and contract. Service endpoint is for the server, where your WCF service is hosted (See Figure 11.6). Service endpoint defines where the service is hosted, what are the bindings and the contract, i.e., methods and interfaces.
While client endpoint is for the client. Client endpoint specifies which service to connect, where it is located, etc.
Code of WCF Server endpoint looks something as shown below.
<service name="WcfService3.Service1" behaviorConfiguration="WcfService3.ServicelBehavior"> <endpoint address='"' binding="wsHTTPBinding" contract="Wcf.Service3 . IServicel"> <identity> <dns value="localhost"/> </identity> </endpoint>
WCF Client end point code looks something as shown below. This is generated when you add service reference using add service reference.
<client> <endpoint address="HTTP: //localhost: 9201/Servicel.svc" binding="wsHTTPBinding" bindingConfiguration="WSHTTPBinding_IServicel" contract="ServiceReferencel.IServicel” name="WSHTTPBinding_IServicel"> <identity> <dns value="localhost" /> </identity> </endpointx/client>