Wednesday, 17 June 2015

WCF Questions

 

 

What is the main disadvantage of using IIS to host a service?


Using IIS to host your services means that you will not be able to support non-HTTP protocols such as TCP, named pipes, and MSMQ. You will have access to the many built-in features available with IIS such as process recycling and message based activation.

How to set the timeout property for the WCF Service client call?

The timeout property can be set for the WCF Service client call using binding tag. 
<client>
<endpoint
binding = "wsHttpBinding"
bindingConfiguration = "LongTimeout"
 
/>
</client>
<bindings>
<wsHttpBinding>
<binding name = "LongTimeout" sendTimeout = "00:04:00"/>
 
</wsHttpBinding>
</bindings>

 

The timeout property can be set for the WCF Service client call using binding tag. If no timeout has been specified, the default is considered as 1 minute.

What is three major points in WCF?

A B C
1) Address  -
Specifies the location of the service 
2) Contract -
Specifies the interface between client and the server. 
3) Binding - 
Specifies how the two parties will communicate in term of transport and   encoding and protocols.

What are the MEPs available in WCF


MEP is the short form for Message Exchange Pattern. In Windows communication foundation, 3 types of Message exchange patterns are allowed.
They are:

1.Data Gram
2.Request and Response
3.Duplex

ConcurrencyMode in WCF.


This property indicates how service supports thread. This property has three values the default is PerSession.

1. Single
2. Multiple
3. Reentrant



What are the different ways to generate proxy in WCF?

 

A service proxy or simply proxy in WCF enables application(s) to interact with WCF Service by sending and receiving messages. It's basically a class that encapsulates service details i.e. service path, service implementation technology, platform and communication protocol etc. It contains all the methods of service contract (signature only, not the implementation). So, when the application interact the service through proxy, it gives the impression that it's communicating a local object.

We can create proxy for a service by using Visual Studio or SvcUtil.exe.

Generating proxy using Visual Studio is simple and straight forward.

->Right click References and choose "Add Service Reference".
->Provide base address of the service on "Add Service Reference" dialog box and click "Go" button. Service will be listed below.
->Provide namespace and click OK.

Visual studio will generate a proxy automatically.

We can generate proxy using svcutil.exe utility using command line. This utility requires few parameters like HTTP-GET address or the metadata exchange endpoint address and a proxy filename i.e. optional.

svcutil http://localhost/MyService/Service1.svc /out:MyServiceProxy.cs 
If we are hosting the service at a different port (other than default for IIS which is 80), we need to provide port number in base address.

svcutil http://localhost:8080/MyService/Service1.svc /out:MyServiceProxy.cs



What is Transport and Message Reliability?

 

Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems. 

Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.

Which namespace is used to access WCF?


System.ServiceModel

Which contract is used to documented the view for error occurred in the service to client in wcf?


Fault Contract is used to documented the view for error occurred in the service to client in wcf.

What is a SOA Service?

SOA is Service Oriented Architecture. SOA service is the encapsulation of a high level business concept. A SOA service is composed of three parts.
1. A service class implementing the service to be provided.
2. An environment to host the service.
3. One or more endpoints to which clients will connect.

 

 



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-Call: Service 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.

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>

 

 

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.

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.
http://www.codeproject.com/images/minus.gif Collapse | Copy Code
[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);
  }
}




WCF service access permission to a role specific user group

    Asp.Net  WCF  Comments (0)
Notice the word "user group"? Here interviewer want to check your practical thinking on WCF service access permission as most of you are familiar with "user role" but not "group". Don't be puzzled. Role based authorization will work here too. The other way can be use of WCF Extensibility feature but that is a lengthy one.
WCF provides us the Role Based Authentication mechanism that can be used for setting service access permission for a specific group. To make it work, we need to do some settings in web.config file as well we need to decorate our those services on which we want to implement this access security.
It can be done in 3 simple steps as :
1)   Enable “aspNetCompatibilityEnable”
http://codepattern.net/Blog/image.axd?picture=%2f2013%2f12%2faspNetCompatibilityTrue.png

2)   Then, we need to specify the Group for which we want to apply security in web.config as:
http://codepattern.net/Blog/image.axd?picture=%2f2013%2f12%2faccessPermissionInWCF.png

3)   And finally specify the security with class that implement your service. This decoration of service is require because, asp.net Compatibility Mode is set to false by default. RequirementMode is set to Allowed.
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
This asp.net compatibility mode setting is done to use ASP features like identity impersonation. This setting applies at the application level (through root web.config file) and can’t be overridden at any folder level web.config files. By default, AspNetCompatibilityRequirementMode is : Allowed.

Questions
 What is MAC in WCF ?
How Event Logging is done in WCF ?

Question : Is overloading possible in WCF? If yes then how?
Answer : Yes, by using [OperationContract(Name="OverloadedName")] But, still outer world will get them with unique and different name. Overloading is a technique to write manageable/maintainable code. But in case of WCF service, uniqueness is required for generating WSDL, and that can be done either by using unique method name or unique OperationContract's name attribute value. Interfaces plays an important role and provides much flexibility for this. We can write many implementations of an interface, and it gives more flexibility plus concise. So why to think on overloading for WCF service methods?  

WCF Service Throttling Behaviour

    Asp.Net  C#  WCF  Comments (0)
WCF provide us a good way of extensibility to customize various WCF capabilities. We can customize Encoding message, Intercepting parameters etc. and extend the behaviour. Throttling behaviour of service plays an important role and can be set behaviour properties according to our business needs. Below are three important properties for optimizing our WCF service behaviour
1. MaxConcurrentCalls
It just specify the maximum number of messages actively processed across all the dispatcher object in a ServiceHost object. Also each channel can have 1 pending message with it that is not counted until WCF begins to process it.
2. MaxInstances
It just specify the maximum number of InstanceContext object in the service. If a message arrives when  InstanceContext objects are at maximum number, then that messages is kept for waiting until an InstanceContext object is closed.
3. MaxConnections
How many maximum number of channels can be accepted by a ServiceHost is defined using this property. This property is mostly used with sessions context. Messages are on channels and these channels are in queue for processing. There can be one pending channel against each listener object. MaxConnections are counted for active channels only and pending channels are not counted in it.

Important Relationship between properties :
ServiceBehaviorAttribute.ConcurrencyMode         <====> ConcurrencyMode.Single
ServiceBehaviorAttribute.InstanceContextMode  <====> MaxInstances

Question/Answer:
  • If MaxConcurrentCalls property has been set to 10 along with ConcurrencyMode = ConcurrencyMode.Single ,which one will get more weight and consider?
Ans :  MaxConcurrentCalls setting is ignored in this case and ConcurrencyMode is given weight and priority.
  • If we set System.ServiceModel.ServiceBehaviorAttribute.InstanceContextMode = InstanceContextMode.PerSession or ServiceBehaviorAttribute.InstanceContextMode = InstanceContextMode.Shareable , then how many context would be there?
Ans:   It will equal to Total number of sessions. 
  • If ServiceBehaviorAttribute.InstanceContextMode=InstanceContextMode.PerCall , then how many context would be there?
Ans: It will equal to the number of concurrent calls.







No comments:

Post a Comment