WCF Interview Questions1

Embed Size (px)

Citation preview

  • 7/28/2019 WCF Interview Questions1

    1/33

    WCF Interview Questions

    What is WCF?

    WCF stands for Windows Communication Foundation (WCF) and is considered as the Microsoft Service-Oriented

    Architecture (SOA) platform for building distributed and interoperable applications. WCF unifies ASMX, Remoting, and

    Enterprise Services stacks and provides a single programming model. WCF services are interoperable and supports all

    the core Web services standards. WCF services also provide extension points to quickly adapt to new protocols and

    updates and integrate very easily with the earlier Microsoft technologies like Enterprise Services, COM and MSMQ.

    What is the version of the .NET framework in which WCF is released?

    WCF - Windows Communication Foundation is released as part of .NET Framework 3.0. WPF (Windows Presentation

    Foundation), WF (Workflow Foundation) and Card Space are also part of .NET Framework 3.0.

    What is the advantage of using WCF over other distributed programming models like Web Services (ASMX),

    .NET Remoting, Enterprise Services stack etc.?

    To understand the advantage of using WCF over other distributed programming models like Web Services (ASMX),

    .NET Remoting, Enterprise Services stack etc, let's consider the following scenario. We have developed an application

    using web services. As we know web services use HTTP protocl and XML SOAP formatted messages, they are good for

    developing interoperable applications in a heterogeneous environment. We have a new client. Our new client is using

    .NET and he wants binary formatted messages over TCP protocol, because interoperability is not a concern and binary

    formatted messages over TCP protocol are much faster than XML SOAP formatted messages over HTTP. To satisfy the

    requirement of this client, now we cannot use our existing web service. So, we have to develop a brand new remoting

    application from the scratch. The business functionality is the same in web services and remoting application. Since ourdifferent clients have different requirements, we ended up creating the same business application using web services

    and remoting technologies. This approach has several disadvantages as listed below.

    1. Developers have to be familiar with two different technologies (Web Services and Remoting).

    2. We end up creating duplicate business applications with different technologies which also leads to maintenance

  • 7/28/2019 WCF Interview Questions1

    2/33

  • 7/28/2019 WCF Interview Questions1

    3/33

    able to generate proxies, the service should enable metadata exchange.

    Define Service Contracts and Operation Contracts in WCF?

    1. Service Contract - An interface that exposes the service operations is usually decorated with the service contract

    attribute. Always provide meaningful Namespace and Name to a service contract as shown in theexample below.

    2. Operation Contract - All methods in a service contract should have OperationContract attribute. You can also

    provide explicit Name, Action and ReplyAction as shown in the example below.

    Can you apply, ServiceContract attribute to a class rather than an interface in WCF?

    Yes, a ServiceContract attribute can be applied either to a class or an interface, but defining service contracts usinginterfaces rather classes has the following benefits.

    1. Defining service contracts using interfaces, removes coupling to service implementation. Later the implementation

    can be changed at will without affecting the clients.

    2. Defining service contracts using interfaces, also allows a service to implement more than 1 contract.

    What is the purpose of MessageParameter attribute in WCF?

    Message Parameter attributes is used to control the parameter and returned object names from a service operation.

    Consider the example below. On the service side, the method parameter name in

    SaveCustomer([MessageParameter(Name = "Customer")] Customer cust) is cust. If we donot use MessageParameter

    attribute, then "cust" is what is exposed as parameter name to the client, which is not very proffesional. So we areusing MessageParameter attribute to expose the method parameter name as Cutomer.

    What are the different options available to serialize complex types that are sent and received between clients

    and services in WCF?The following are the different options available to serialize complex types that are exchanged between clients and

    services in WCF. These options have their own advantages and disadvantages. A data contract is the preferred way to

    serialize complex types in WCF.

    1. Serializable types - Us the Serializable attribute on the type that you want to serialize

    2. Data contracts - Use DataContract attribute on the type and DataMember attribute on every member of the type,

    that you want to serialize. You can apply DataMember attribute either on a filed or a property.

    3. Known types - Use Known types to enable polymorphic behavior in service contracts.

    4. IXmlSerializable - IXmlSerializable types provide XSD schema to Web Services Description Language(WSDL) and

    metadata exchange (MEX).

    What is the disadvantage of using Serializable attribute to serialize a complex type that is sent and receivedbetween clients and services in WCF?

    When we decorate a class with Serializable attribute, all the fields of the class are serialized regardless of the

    accessibility. We dont have control on what to serialize and what not to serialize. We also will not have any control

    over naming conventions or data types.

    http://4.bp.blogspot.com/-A_uCp0uTNc8/TWANKkoGVtI/AAAAAAAAADA/Mw1Hsco04L4/s1600/MessageParameter.jpghttp://2.bp.blogspot.com/-mIbKUJ5ZVfI/TWAMm5OKaKI/AAAAAAAAAC8/QrZ4ED5fdoQ/s1600/WCF+Operation+Contract.jpghttp://4.bp.blogspot.com/-I_tly-B54YM/TWALGyEGXsI/AAAAAAAAAC4/KJtJ28YNFEE/s1600/WCF+Service+Contract.jpghttp://4.bp.blogspot.com/-A_uCp0uTNc8/TWANKkoGVtI/AAAAAAAAADA/Mw1Hsco04L4/s1600/MessageParameter.jpghttp://2.bp.blogspot.com/-mIbKUJ5ZVfI/TWAMm5OKaKI/AAAAAAAAAC8/QrZ4ED5fdoQ/s1600/WCF+Operation+Contract.jpghttp://4.bp.blogspot.com/-I_tly-B54YM/TWALGyEGXsI/AAAAAAAAAC4/KJtJ28YNFEE/s1600/WCF+Service+Contract.jpghttp://4.bp.blogspot.com/-A_uCp0uTNc8/TWANKkoGVtI/AAAAAAAAADA/Mw1Hsco04L4/s1600/MessageParameter.jpghttp://2.bp.blogspot.com/-mIbKUJ5ZVfI/TWAMm5OKaKI/AAAAAAAAAC8/QrZ4ED5fdoQ/s1600/WCF+Operation+Contract.jpghttp://4.bp.blogspot.com/-I_tly-B54YM/TWALGyEGXsI/AAAAAAAAAC4/KJtJ28YNFEE/s1600/WCF+Service+Contract.jpg
  • 7/28/2019 WCF Interview Questions1

    4/33

    What is the preferred way for serializing complex types in WCF?

    The preferred way for serializing complex types in WCF is to use data contracts. Using Data Contracts provides us with

    the following advantages.

    1. Using DataMember attribute, you can control which members of the class to serialize.

    2. You can also control the order in which members are serialized using Order parameter of the DataMember attribute.

    3. You can also provide explicit Name to the serialized members using Name parameter of the DataMember attribute.

    4. You can also specify if a member is required or optional using IsRequired parameter of the DataMember attribute.

    Consider the example below which uses Name, IsRequired and Order parameters of the DataMember attribute to

    serialize CustomerId property. By the way DataMember attribute can be used with either fields or properties. If you

    donot specify the order in which members are serialized, then by default alphabetical ordering is done by the

    DataContractSerializer.

    What is the best way to serialize Polymorphic Types in WCF?

    The best way to serialize Polymorphic Types in WCF is to use KnownType attribute on the parent type as shown in the

    example below. CorporateCustomer and PremiumCustomer classes inherit from Customer class,and hence we can

    associate CorporateCustomer and PremiumCustomer types as known types in 3 different ways depending on the

    project requirement.

    1. Associate known types to the base types themselves.

    2. Associate known types to particular operations.

    3. Associate known types to the service contract as a whole.

    In Example 1, we are associating known types, CorporateCustomer and PremiumCustomer to the base type, Customer.

    In Example 2, we are associating known type, Corporate Customer on SaveCorporateCustomer(Customer customer)

    and GetCorporateCustomer(int CustomerId) operations using ServiceKnownType attribute.

    http://2.bp.blogspot.com/-At_lZGxklks/TWAVflyN9oI/AAAAAAAAADQ/51zV4rXNBmQ/s1600/E2.jpghttp://3.bp.blogspot.com/-2kMU7pfjTPA/TWAVFI78CSI/AAAAAAAAADI/8dAMkaM9bPA/s1600/E1.jpghttp://2.bp.blogspot.com/-as-V72Nvx5o/TWATRJHtPPI/AAAAAAAAADE/5EBYUPuIRa8/s1600/DataMember.jpghttp://2.bp.blogspot.com/-At_lZGxklks/TWAVflyN9oI/AAAAAAAAADQ/51zV4rXNBmQ/s1600/E2.jpghttp://3.bp.blogspot.com/-2kMU7pfjTPA/TWAVFI78CSI/AAAAAAAAADI/8dAMkaM9bPA/s1600/E1.jpghttp://2.bp.blogspot.com/-as-V72Nvx5o/TWATRJHtPPI/AAAAAAAAADE/5EBYUPuIRa8/s1600/DataMember.jpghttp://2.bp.blogspot.com/-At_lZGxklks/TWAVflyN9oI/AAAAAAAAADQ/51zV4rXNBmQ/s1600/E2.jpghttp://3.bp.blogspot.com/-2kMU7pfjTPA/TWAVFI78CSI/AAAAAAAAADI/8dAMkaM9bPA/s1600/E1.jpghttp://2.bp.blogspot.com/-as-V72Nvx5o/TWATRJHtPPI/AAAAAAAAADE/5EBYUPuIRa8/s1600/DataMember.jpg
  • 7/28/2019 WCF Interview Questions1

    5/33

    In Example 3, we are associating known types, Corporate Customer and Premium Customer to the service contract

    ICustomerService as a whole.

    It is also possible to specify known types in a configuration file rather than in code. Example 4 shows how to specify

    known types in configuration.file.

    Explain the significance of MessageContract attribute?

    OR

    Why and when do you use MessageContract attribute?

    There are several advantages of using MessageContract attribute in WCF. MessageContract attribute can be used for

    1. Adding custom headers to the message.

    2. Controling message wrapping.

    3. Controling signing and encryption of messages.

    MessageContract attribute provides us with greater control over message headers and body elements.

    MessageContract attribute converts a type to a SOAP message. The example below shows how to use IsWrapped and

    ProtectionLevel parameters of MessageContract attribute. You may also set an explicit Name and Namespace.

    Message Contract attribute is supported by MessageHeader attribute and MessageBodyMember attribute. You can

    apply MessageHeader attribute to fields or properties of message contract. This is a simple technique for creating

    custom headers.You can provide Name, Namespace and ProtectionLevel. You may also set SOAP protocol settings like

    Relay, Actor, MustUnderstand.

    MessageBodyMember attribute can also be Applied to fields or properties of message contract.Can have several bodyelements. This is equivalent to multiple parameters in operation and this is the only way to return multiple complex

    types. It is suggested as a good practice to always supply Order. You can also set Name, Namespace, ProtectionLevel.

    The example below shows how to use MessageHeader and MessageBodyMember attributes.

    http://4.bp.blogspot.com/-UDL08Up3bGg/TWAYFNg52_I/AAAAAAAAADo/0_PFSSYLrbc/s1600/MessageContract.jpghttp://4.bp.blogspot.com/-AOPzWVDb5oU/TWAWRHa5ibI/AAAAAAAAADg/G9IzY96-wnU/s1600/E4.jpghttp://2.bp.blogspot.com/-GX-9Phaz8cM/TWAV5aU2q4I/AAAAAAAAADY/GBDsXD2L9ZQ/s1600/E3.jpghttp://4.bp.blogspot.com/-UDL08Up3bGg/TWAYFNg52_I/AAAAAAAAADo/0_PFSSYLrbc/s1600/MessageContract.jpghttp://4.bp.blogspot.com/-AOPzWVDb5oU/TWAWRHa5ibI/AAAAAAAAADg/G9IzY96-wnU/s1600/E4.jpghttp://2.bp.blogspot.com/-GX-9Phaz8cM/TWAV5aU2q4I/AAAAAAAAADY/GBDsXD2L9ZQ/s1600/E3.jpghttp://4.bp.blogspot.com/-UDL08Up3bGg/TWAYFNg52_I/AAAAAAAAADo/0_PFSSYLrbc/s1600/MessageContract.jpghttp://4.bp.blogspot.com/-AOPzWVDb5oU/TWAWRHa5ibI/AAAAAAAAADg/G9IzY96-wnU/s1600/E4.jpghttp://2.bp.blogspot.com/-GX-9Phaz8cM/TWAV5aU2q4I/AAAAAAAAADY/GBDsXD2L9ZQ/s1600/E3.jpg
  • 7/28/2019 WCF Interview Questions1

    6/33

    DataContract enables us to define the structure of the data. This data is sent in the body of our SOAP (Simple Object

    Access Protocol) messages. These messages may be of either inbound (request) or outbound (response) type. Amessage is nothing but a packet and WCF uses this packet to transfer information from source to destination. This

    message contains an envelope, header and body.

    A Message Contract is used to control the structure of a message body and serialization process. It is also used to

    send / access information in SOAP headers.

    Message Contract Attributes

    MessageContractAttribute

    MessageHeaderAttribute MessageBodyMemberAttribute

    MessageContractAttribute

    The MessageContract Attribute is applied to a class or structure to define our own message structure, as in:

    [MessageContract()]

    publicclassAuthorRequest

    {

    }

    Properties of MessageContractAttribute

    1. public bool HasProtectionLevel { get; }HasProtectionLevel gets a value that indicates whether the message has a protection level.

    http://3.bp.blogspot.com/-Qa4565MrFgw/TWAZAUZLa_I/AAAAAAAAADw/v8j5otQ30vo/s1600/MessageHeaderandBody.jpghttp://3.bp.blogspot.com/-Qa4565MrFgw/TWAZAUZLa_I/AAAAAAAAADw/v8j5otQ30vo/s1600/MessageHeaderandBody.jpg
  • 7/28/2019 WCF Interview Questions1

    7/33

    It returns true if the message must be encrypted, signed, or both; otherwise false. The default is false.

    2. public bool IsWrapped { get; set; }IsWrapped gets or sets a value that specifies whether the message body has a wrapper element.

    It returns true if the message body has a wrapper element; otherwise, false. The default is true.

    3. public ProtectionLevel ProtectionLevel { get; set; }ProtectionLevel gets or sets a value that specified whether the message must be encrypted, signed, or both.

    It returns one of the System.Net.Security.ProtectionLevel values. The default is

    System.Net.Security.ProtectionLevel.None.

    4. public string WrapperName { get; set; }WrapperName gets or sets the name of the wrapper element of the message body.

    It returns the name of the wrapper element in the message body.

    5. public string WrapperNamespace { get; set; }WrapperNamespace gets or sets the namespace of the message body wrapper element.

    It returns the wrapper element namespace.

    For example:

    [MessageContract(IsWrapped = false,ProtectionLevel=ProtectionLevel.None)]

    publicclassAuthorRequest

    {

    }

    MessageHeaderAttribute

    MessageHeaderAttribute is applied to the members of the MessageContract to declare the members within the

    message header; see:

    [MessageContract(IsWrapped = false,ProtectionLevel=ProtectionLevel.None)]

    publicclassAuthorRequest

    {

    [MessageHeader()]

    publicstring AuthorId;

    }

    Properties of MessageHeaderAttribute

    1. public string Name { get; set; }Name specifies the name of the element that corresponds to this member.

    It returns the name of the element that corresponds to this member. This string must be a valid XML element

    name.

    2. public string Namespace { get; set; }Namespace specifies the namespace of the element that corresponds to this member.

    It returns a namespace URI of the element that corresponds to this member.

    3. public ProtectionLevel ProtectionLevel { get; set; }ProtectionLevel specifies whether the member is to be transmitted as-is, signed, or signed and encrypted.

  • 7/28/2019 WCF Interview Questions1

    8/33

  • 7/28/2019 WCF Interview Questions1

    9/33

    2. The return type of the OperationContract is of MessageContractType or Void type.

    Now add the following lines of code to your Interface.

    Now add an implementation of the above operation contract in the service class.

  • 7/28/2019 WCF Interview Questions1

    10/33

    Test Client Output (IsWrapped = false)

    Insert 'db2972' as the input for the AuthorIdentity parameter; see:

    SOAP Request

    An AuthorIdentity element is in the SOAP request as we pass this under the MessageHeader. And the Body element is

    empty because we are not passing any value.

    SOAP Response

    In response we get author information directly under the body element as we set IsWrapped to false.

    Test Client Output (IsWrapped = true)

    Now change the code, set IsWrapped to true in the MessageContract and once again check the result in Test Client.

  • 7/28/2019 WCF Interview Questions1

    11/33

    SOAP Request

    AuthorRequest element is empty and is added under the body element because we set IsWrapped to true.

    SOAP Response

    In the same way in the response also the AuthorResponse element is added under the body element.

    Data contracts are used to define the data structure. Messages that are simply a .NET typed convenience for

    generating the XML for the data you want to pass.

    Message contracts are preferred only when there is a need to "control" the layout of your message (the SOAP

    message); for instance, adding specific headers/footer/etc to a message.

    What is WS-Policy?

    OR

    What is Web Services Policy?

    Web Services Policy or WS-Policy is an interoperable standard for describing policies that influence communication

    with the clients. Usually WS-Policy is included in the WSDL contract exposed by the WCF service, although it is

    optional.

    What is the use of WS-Policy?

    WS-Policy is generally used for

    1. Describing protocols for accessing operations

  • 7/28/2019 WCF Interview Questions1

    12/33

    2. Security

    3. Reliable messaging

    4. Transactions

    5. Message encoding (Message Transmission Optimization Mechanism [MTOM])

    6. Other protocols

    you can specify the above settings in WSDL directly without a policy section, but the disadvantage is that, once

    published, the WSDL contract is final. If the clients has to communicate with a WCF service that has changed the

    settings in the WSDL, the clients need to rebuild the proxy and configuration or at least the changes to the WSDLcontract must support backward compatibility.

    The advantage of using WS-Policy is that it can change over time, and the clients can discover the changed policy to

    communicate via metadata exchange. But keep in mind that, you can only change the policy safely if clients are

    positioned to handle dynamic changes

    Is WCF Contracts version tolerant?

    Yes, WCF contracts are version tolerant by default. Service contracts, data contracts, and message contracts forgive

    missing and non required data. They also Ignore any superfluous or additional data sent by the client to the service.

    The DataContractSerializer provides tolerance. Reasonable changes can be made without impacting existing clients.

    The following table summarizes the changes to a service contract and impact on existing clients.

    What is IExtensibleDataObject?

    OR

    What is the advantage and disadvantage of implementing IExtensibleDataObject?

    WCF guidelines recommend enhancing all data contracts with support ofIExtensibleDataObject interface, to

    preserve unexpected data from clients. During deserialization, superfluous data is placed in a dictionary on the service

    side and during serialization, the same data is written as XML as it was originally provided by the client. This is very

    http://1.bp.blogspot.com/-VyWKuj0PPuw/TWLqKtEKcEI/AAAAAAAAAD8/HOznkcelrxs/s1600/ServiceContractChanges.jpg
  • 7/28/2019 WCF Interview Questions1

    13/33

    useful to preserve data from version 2.0 services at a version 1.0 client. It is also useful in case where downstream calls

    from version 2.0 services go to other services handling version 1.0.

    However, there is also a disadvantage of implementing IExtensibleDataObject. It carries risks of denial of service

    (DoS) and unnecessary use of server resources.

    We can turn on and off, the support for IExtensibleDataObject either in code declaratively using attributes or in the

    configuration file as shown below.

    Disabling support for IExtensibleDataObject in Code using attributes

    Disabling support for IExtensibleDataObject in configuration

    What are SOAP Faults in WCF?

    Common language runtime (CLR) exceptions do not flow across service boundaries. At the maximum, a CLR exception

    may propagate up to the service tier from business components. Unhandled CLR exceptions reach the service channel

    and are serialized as SOAP faults before reporting to clients. An unhandled CLR exception will fault the service channel,

    taking any existing sessions with it. That is why it is very importatnt to convert the CLR exceptions into SOAP faults.

    Where possible, throw fault exceptions

    SOAP faults are standards based and interoperable. There are 2 formats used by SOAP faults, SOAP 1.1 and SOAP 1.2.

    SOAP format depends on the binding used.

    What happens if there is an unhandled exception in WCF?

    If there is an unhandled exception in WCF, the the service model returns a general SOAP fault, that does not include

    any exception specific details by default. However, you can include exception details in SOAP faults, using

    IncludeExceptionDetailsInFaults attribute. If IncludeExceptionDetailsInFaults is enabled, exception details

    including stack trace are included in the generated SOAP fault. IncludeExceptionDetailsInFaults should be enabled for

    debugging purposes only. Sending stack trace details is risky.

    What are the 2 ways to enable IncludeExceptionDetailsInFaults for a WCF service?

    Either programmatically or thru configuration.

    To enable thru code use ServiceBehaviorAttribute as shown below:

    [ServiceBehaviourAttribute(IncludeExceptionDetailsInFaults=true)]

    public classPragimService : IPragimService

    To enable using configuration use servicedebug element as shown below

    http://2.bp.blogspot.com/-fpvQ1ViMTdg/TWg7ht_6roI/AAAAAAAAAEE/5_fUdmeYwPQ/s1600/IExtensible+Data+Object.jpghttp://2.bp.blogspot.com/-fpvQ1ViMTdg/TWg7ht_6roI/AAAAAAAAAEE/5_fUdmeYwPQ/s1600/IExtensible+Data+Object.jpg
  • 7/28/2019 WCF Interview Questions1

    14/33

    What are bindings in WCF?

    Bindings in WCF define the configuration of communication channel between clients and services. Binding specifies

    1. Transport Protocol

    2.Message encoding3. Security Mechanism

    4. Reliable Messaging

    5. Transactions Support

    What are different Transport protocols available in WCF?

    1.TCP

    2. HTTP

    3. Named Pipes

    4. MSMQ

    What message encoding formats are available in WCF?

    1. Text - For interoperability

    2. MTOM (Transmission Optimization Mechanism) - For transferring large objects

    3.Binary - For speed

    What are the 2 ways available for configuring bindings in WCF?

    1. Declaratively using a configuration file

    2. Programmatically in the code.

    Using configuration file has several advantages.

    List a few standard bindings available in WCF?

    1. BasicHttpBinding

    2. NetPeerTcpBinding

    3. WSFederationHttpBinding

    4. NetNamedPipeBinding

    5. WSHttpBinding

    6. WSDualHttpBinding

    7. NetTcpBinding

    8. NetMsmqBinding

    9. MsmqIntegrationBinding

    A Binding specifies which transport protocol to use, what message format and which any of the ws* protocols we wantto use to a particular endpoint.

    https://lh4.googleusercontent.com/-YhFSoUcmPSg/TX_tigVqoLI/AAAAAAAAAEM/rm85IGINT-A/s1600/IncludeExceptionDetailsInFaults.jpg
  • 7/28/2019 WCF Interview Questions1

    15/33

    BasicHttpBinding

    Replacement for earlier Web Service based on ASMX (Active Server Methods) Supports:

    o HTTP - Hypertext Transfer Protocolo HTTPS - Hypertext Transfer Protocol over SSLo MTOM - Message Transmission Optimization Mechanism encoding methods.

    wsHttpBinding

    Uses SOAP over HTTP and supports reliability, transactions and security over the internet. Supports:

    o HTTP - Hypertext Transfer Protocolo HTTPS - Hypertext Transfer Protocol over SSLo MTOM - Message Transmission Optimization Mechanism encoding methods.

    wsDualHttpBinding

    Used for duplex service contract because it supports bidirectional communication.webHttpBinding

    Sends information directly over HTTP or HTTPS without creating a SOAP envelope It is a good choice when SOAP is not required by the client

    NetTcpBinding

    Used to send binary-encoded SOAP messages from one computer to another Uses TCP (Transmission Control Protocol) and includes support for reliability, transactions and security

    NetPeerTcpBinding

    Used for peer-to-peer communication over TCP Communication should occur between two or more computers

    netNamedPipeBinding

    Binary encoded SOAP messages are sent over named pipes Used on a single WCF computer

    netMSMQBinding

    Queued binding is used to send binary-encoded SOAP messages over MSMQ Communication should occur between two computers

    Can you create a customized binding in WCF?

    Yes, bindings in WCF are completely extensible and we can create a customized one.

    Can you overload methods in a WCF service?

    Yes, it is possible to overload methods in a WCF service, but the names of the exposed operation contracts must be

    unique. To achieve this we can use the Name property ofOperationContractAttribute. Let us understand this with an

    example.

  • 7/28/2019 WCF Interview Questions1

    16/33

    If I have the WCF service designed as shown below, the service compiles without any issues.

    When we try to run the service, we will get InvalidOperationException.

    What are the different message exchanging patterns available in WCF?

    There are 3 main different message exchanging patterns available in WCF.

    1. Request-Reply - In the request-reply pattern, a client application sends a message to a WCF service and then waits

    for a reply. This is the classic and most commonly used message exchange pattern in WCF.

    2. One-Way - In a one way message exchange pattern no response is sent back, even if there is an exception. In the

    one-way message exchange pattern, a client application sends a message to a WCF service but the service does not

    send a reply message to the client. You can use this pattern when a client requests the service take an action but does

    not need to wait for a reply.

    3. Duplex - In the request/reply and one-way message exchange patterns, only the client can initiate communication.

    In the duplex pattern, both the client and the service can initiate communication. The client calls a method of theservice. The service can then use a client callback to call a method in the client. You can use this pattern when you

    want the service to send a notification or alert to the client after the client has called the service.

    What is the default message exchange pattern used in WCF?

    Request/Reply

    How do you setup a one way operation?

    Set OperationContractAttribute's IsOneWay property to true. An example is shown below.

    What is MTOM?

    MTOM stands for Message Transmission Optimization Mechanism and is an Interoperable standard that reduces the

    overhead of large binary data transfera. Removes bloat and processing overhead of base64 encoded data. Improves

    overall message transfer performance.

    To correct this we can use the Name property of OperationContractAttribute as shown below. After this change, the

    service works fine both at compile and runtime.

  • 7/28/2019 WCF Interview Questions1

    17/33

    What is WCF throttling?

    WCF throttling enables us to regulate the maximum number of WCF instances, concurrent calls and concurrent

    sessions. The basic purpose is to control our WCF service performance by using Service throttling behavior.

    In the configuration file we can set this behavior as follows:

  • 7/28/2019 WCF Interview Questions1

    18/33

    Single: at a given time, only a single request can be processed by a WCF service instance. Other requests will be

    waiting until the first one is fully served.

    Multiple: multiple requests can be served by multiple threads of a single WCF service instance.

    Reentrant: a single WCF service instance can process one request at a given time but the thread can exit the service to

    call another service.

    We can apply these concurrency settings by putting ConcurrencyMode property in ServiceBehavior as follows:

    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple]

    Public classMyService : IMyService

    {

    }

    What are the various ways to expose WCF Metadata?

    By default, WCF doesn't expose metadata. We can expose it by choosing one of the following ways:

    1. In the configuration file, by enabling metadata exchange as follows:

    2. ServiceHost can expose a metadata exchange endpoint to access metadata at runtime.using (ServiceHost host = new ServiceHost(typeof(MyService)))

    {

    ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();

    behavior.HttpGetEnabled = true;

    host.Description.Behaviors.Add(behavior);

    host.Open();

    Console.WriteLine("My Service here..........");

    Console.ReadLine();

  • 7/28/2019 WCF Interview Questions1

    19/33

    host.Close();

    }

    What is mexHttpBinding in WCF?

    To generate a proxy, we need service metadata and mexHttpBinding returns service metadata.

    If we look into our configuration file, the service will have an endpoint with mexHttpBinding as follows:

    and the service metadata behavior will be configured as follows:

    Before deployment of the application to a production machine, it should be disabled.

    To support other protocols, related bindings are mexHttpBinding, mexHttpsBinding and mexTcpBinding.

    What is a Service Proxy in WCF?

    A service proxy or simply proxy in WCF enables application(s) to interact with a WCF Service by sending and receivingmessages. 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 a service contract (signature only, not the

    implementation). So, when the application interacts with the service through the proxy, it gives the impression that it's

    communicating a local object.

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

    What are the various ways to generate a proxy in WCF?

    Generating a proxy using Visual Studio is simple and straight forward.

    1. Right-click References and choose "Add Service Reference".2. Provide the base address of the service on "Add Service Reference" dialog box and click the "Go" button.

    The service will be listed below.

    3. Provide the namespace and click OK.Visual Studio will generate a proxy automatically.

    We can generate a proxy using the svcutil.exe utility using the command line. This utility requires a few parameters like

    HTTP-GET address or the metadata exchange endpoint address and a proxy filename i.e. optional. For example:

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

    If we are hosting the service at a different port (other than the default for IIS which is 80), we need to provide a port

    number in the base address. For example:

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

    For parameter details regarding svcutil, please follow the MSDN link

    What is the difference between use of ChannelFactory and Proxies in WCF?

    If we have control over the server and client, then the ChannelFactory is a good option because it relies on having local

    interfaces that actually describes the service i.e. service contract.

    On the other hand, if we don't have control over the server and only have a WSDL/URL, then it's better to generate a

    proxy using Visual Studio or SvcUtil.

  • 7/28/2019 WCF Interview Questions1

    20/33

    SvcUtil is a better option as compared to Visual Studio because we have more control using SvcUtil.

    How to create proxy for Non-WCF Services?

    In case of Non-WCF Services, we can create a proxy by either using Visual Studio or the svcUtil.exe tool by pointing to

    a WSDL of the non-WCF service. In this scenario, we can't create a proxy through a ChannelFactory or manually

    developing a proxy class because we don't have local interfaces i.e. a service contract.

    Breifly explain Automatic Activation in WCF?

    Automatic activation means the service starts and serves the request when a message request is received, but the

    service doesn't need to be running in advance.

    There are a few scenarios in which the service needs to be running in advance. For example, in the case of Self-

    Hosting.

    What is Reliable Messaging in WCF?

    We know that networks are not perfect enough and might drop signals or in some environments there can be the

    possibility of some messages being in the wrong order during message exchange.

    WCF allows us to ensure the reliability of messaging by implementing the WS-ReliableMessaging protocol. Here is

    how you can configure reliable messaging in WCF:

    8. What are Reliable Sessions in WCF?

    Reliable sessions actually ensure that the caller for messages will know about the lost message(s) but it can't guarantee

    the delivery of message(s).

    There is a misconception about reliable sessions that it ensures the session will never expire or stays for a very long

    time. This we can do using timeout for sessions.

    9. Briefly explain WCF RESTfull services?

    RESTful services are those which follow the REST (Representational State Transfer) architectural style.

    As we know, WCF allows us to make calls and exchange messages using SOAP over a variety of protocols i.e. HTTP,

    TCP, NamedPipes and MSMQ etc. In a scenario, if we are using SOAP over HTTP, we are just utilizing HTTP as a

    transport. But Http is much more than just a transport.

    So, when we talk about REST architectural style, it dictates that "Instead of using complex mechanisms like CORBA,

    RPC or SOAP for communication, simply HTTP should be used for making calls".

    RESTful architecture use HTTP for all CRUD operations like (Read/CREATE/Update/Delete) using simple HTTP verbs like

    (GET, POST, PUT, and DELETE). It's simple as well as lightweight.

    10. Briefly explain WCF Data Services?

  • 7/28/2019 WCF Interview Questions1

    21/33

    WCF Data services, previously known as ADO.NET data services, are basically based on OData (Open Data Protocol)

    standard which is a REST (Representational State Transfer) protocol.

    The Open Data Protocol (OData) is a Web protocol for querying and updating data that provides a way to unlock your

    data and free it from silos that exist in applications today. OData does this by applying and building upon Web

    technologies such as HTTP, Atom Publishing Protocol (AtomPub) and JSON to provide access to information from a

    variety of applications, services, and stores. The protocol emerged from experiences implementing AtomPub clients

    and servers in a variety of products over the past several years. OData is being used to expose and access informationfrom a variety of sources including, but not limited to, relational databases, file systems, content management systems

    and traditional Web sites.

    Difference between BasicHttpBinding and WsHttpBinding with respect to security?

    Please follow differences between BasicHttpBinding and WsHttpBinding for more detailed discussion, but the basic

    difference with respect to security is as follows:

    As WsHttpBinding supports the advanced WS-* specification, it has a lot more security options available. For

    example, it provides message-level security i.e. message is not sent in plain text. Also it supports WS-Trust and WS-

    Secure conversations.

    While in the case ofBasicHttpBinding, it has fewer security options, or we can say, there is no security provided, by

    default. At the transport level, it can provide confidentiality through SSL.

    6. Please explain about authorization options supported in WCF?

    Authorization is a core feature of security in WCF, which supports various authorization types.

    Role-based authorization is the most common authorization approach being used. In this approach, anauthenticated user has assigned roles and the system checks and verifies that either a specific assigned role can

    perform the operation requested.

    An Identity-based authorization approach basically provides support for identity model features which is considered

    to be an extension to role-based authorization option. In this approach, the service verifies client claims against

    authorization policies and accordingly grant or deny access to operation or resource.

    The Resource-based authorization approach is a bit different because it's applied on individual resources and

    secured using Windows Access Control Lists (ACLs).

    What is a fault contract?

    Normally, by default, when some exception occurs at a WCF service level, it will not be exposed as it is to the client.

    The reason is that the WCF exception is a CLR exception and it doesn't make sense to expose it outside of the CLR

    because it contains internal details of service code like stack trace. So, WCF handles and returns error details to the

    client using a Fault Contract.

    "So, a fault contract is a contract that contains the details of possible exception(s) that might occur in service code."

    [ServiceContract]

    publicinterfaceIService1

    {[OperationContract]

    [FaultContract(typeof(MyFaultDetails))]

    int MyOperation1();

    }

  • 7/28/2019 WCF Interview Questions1

    22/33

    [DataContract]

    publicclassMyFaultDetails

    {

    [DataMember]

    publicstring ErrorDetails { get; set; }

    }

    In the implementing service

    publicint MyOperation1()

    {

    Try{

    //Do something......

    }catch()

    {

    MyFaultDetails ex = new MyFaultDetails();

    ex.ErrorDetails = "Specific error details here.";

    thrownew FaultException(ex,"Reason: Testing.....");}

    }

    2. A user has a service with a one-way operation that includes a fault contract, and he gets an exception when

    he tries to host the service. Why?

    This is true, because, to return faults, the service requires some form of a two-way communication channel, which is

    not present in one-way operations.

    3. What are the core security concepts supported by WCF?

    There are four core security features:1. Confidentiality: It's a confirmation about the recipient. Only the valid recipient can read the message when it

    passed between service and client

    2. Integrity: Is to ensure that message received is not being tempered or changed during an exchange.3. Authentication: Is a way for the parties (sender and receiver) to identify each other.4. Authorization: Ensures what actions an authenticated user can perform.

    4. Difference between Message Level security and Transport Level security?

    Security can be configured at different levels in Windows Communication Foundation; they are:

    1. Transport Level Security2. Message Level Security

    What are the core security features that WCF addresses?

    There are four core security features that WCF addresses:

    Confidentiality: This feature ensures that information does not go in to the wrong hands when it travels from thesender to the receiver.

    Integrity: This feature ensures that the receiver of the message gets the same information that the sender sentwithout any data tampering.

    Authentication: This feature verifies who the sender is and who the receiver is. Authorization: This feature verifies whether the user is authorized to perform the action they are requesting from the

    application.

  • 7/28/2019 WCF Interview Questions1

    23/33

    What is transport level and message level security?

    When we talk about WCF security, there are two aspects. The first is the data and the second is the medium on which

    the data travels, i.e., the protocol. WCF has the ability to apply security at the transport level (i.e., protocol level) and

    also at message level (i.e., data).

    Figure: Transport and Message level 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 protocols like TCP, HTTP, MSMQ, etc., and each of these

    protocols has their own security mechanisms. One of the common implementations of transport level security is

    HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security mechanism. No coding change is

    required, its more about 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. One ofthe common ways of implementing message level security is by encrypting data using some standard encryption

    algorithm.

    For which bindings are transport, message, and mixed mode supported?

    Note: The below table is taken from the book Pro WCF: Practical Microsoft SOA Implementation -- Chris Peiris and

    Denis Mulder Apress 2007.

    Below is a table which shows which mode is supported for each binding. We are not discussing mixed mode. Its

    nothing but a combination of transport and mixed modes. For instance, data encrypted and passed over WsHttp using

    HTTPS is a mixed mode security. Encryption is nothing but message security and HTTPS is a transport mode. In

    combination, they form mixed mode.

    Binding Transport Mode? Message Mode? Mixed Mode?

    BasicHttpBinding Yes Yes Yes

  • 7/28/2019 WCF Interview Questions1

    24/33

    Binding Transport Mode? Message Mode? Mixed Mode?

    WsHttpBinding Yes Yes Yes

    WsDualHttpBinding No Yes No

    NetTcpBinding Yes Yes Yes

    NetNamedPipeBinding Yes No No

    NetMsmqBinding Yes Yes No

    MsmqIntegrationBinding Yes No No

    So what are the scenarios, advantages, and disadvantages of transport and message security?

    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 its an intranet type of solution, this is the 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 hardwareaccelerators to enhance performance.

    There is a lot of interoperability support and

    communicating clients do not need to understand WS

    security as its built in the protocol itself.

    Provides end to end security as its not

    dependent on the protocol. Any

    intermediate hop in the network does notaffect the application.

    Supports a wide set of security options as

    it is not dependent on the protocol. We

    can also implement custom security.

    Disadvantages As its a protocol implemented security, it works only

    point to point.

    As security is dependent on protocol, it has limited

    security support and is bound to the protocol security

    limitations.

    Needs application refactoring to

    implement security.

    As every message is encrypted and

    signed, there are performance issues.

    Does not support interoperability with old

    ASMX web services.

  • 7/28/2019 WCF Interview Questions1

    25/33

    Figure: Route paths

    Events

    Events allow the client or clients to be notified about something that has occurred on the service side. An event may

    result from a direct client call, or it may be the result of something the service monitors. The service firing the event is

    called the publisher, and the client receiving the event is called the subscriber.

    Publisher will not care about order of invocation of subscriber. Subscriber can be executed in any manner. Implementation of subscriber side should be short duration. Let us consider the scenario in which you what to

    publish large volume of event. Publisher will be blocked, when subscriber is queued on previous subscription

    of the event. These make publishers to put in wait state. It may lead Publisher event not to reach other

    subscriber. Large number of subscribers to the event makes the accumulated processing time of each subscriber could

    exceed the publisher's timeout

    Managing the list of subscribers and their preferences is a completely service-side implementation. It will notaffect the client; publisher can even use .Net delegates to manage the list of subscribers.

    Event should always one-Way operation and it should not return any valueThrottling

    WCF throttling provides some properties that you can use to limit how many instances or sessions are created at the

    application level. Performance of the WCF service can be improved by creating proper instance.

    Attribute Description

    maxConcurrentCallsLimits the total number of calls that can currently be in progress across all service instances.

    The default is 16.

    maxConcurrentInstancesThe number of InstanceContext objects that execute at one time across a ServiceHost. The

    default is Int32.MaxValue.

    maxConcurrentSessions A positive integer that limits the number of sessions a ServiceHost object can accept. The

    default is 10.

  • 7/28/2019 WCF Interview Questions1

    26/33

    Instance Deactivation

    In Instance Management System tutorial, you learn how to create sessionful service instance. Basically service instance

    is hosted in a context. Session actually correlated the client message not to the instance, but to the context that host it.

    When session starts, context is created and when it closes, context is terminated. WCF provides the option of

    separating the two lifetimes and deactivating the instance separately from its context.

    ReleaseInstanceMode property of the OberationalBehaviorattribute used to control the instance in relation to the

    method call.

    Followings are the list Release mode available in the ReleaseInstanceMode

    1. RealeaseInstanceMode.None2. RealeaseInstanceMode.BeforeCall3. RealeaseInstanceMode.AfterCall4. RealeaseInstanceMode.BeforeAndAfterCall

    Below code show, how to add the 'ReleaseInstanceMode' property to the operational behavior.

    [ServiceContract()]

    public interface ISimpleCalculator

    {

    [OperationContract()]

    int Add(int num1, int num2);

    }

    [OperationBehavior(ReleaseInstanceMode=ReleaseInstanceMode.BeforeCall]

    public int Add(int num1, int num2){

    return num1 + num2;

    }

    ReleaseInstanceMode.None

    This property means that it will not affect the instance lifetime. By default ReleaseInstanceMode property is set to

    'None'.

    ReleaseInstanceMode.BeforeCall

    This property means that it will create new instance before a call is made to the operation.

    If the instance is already exist,WCF deactivates the instance and calls Dispose() before the call is done. This is designed

    to optimize a method such as Create()

    ReleaseInstanceMode.AfterCall

    This property means that it will deactivate the instance after call is made to the method.

  • 7/28/2019 WCF Interview Questions1

    27/33

  • 7/28/2019 WCF Interview Questions1

    28/33

    }

    The XmlSerializerFormat attribute above the ServiceContract means this serializer is for all operation contracts. You

    can also set a separate contract for each operation.

    Each serializer calls different algorithms for mapping between .Net object and WCF messages. And each serializer

    produces a slightly different message.

    We can use SvcUtil.exe to move between .Net types and XSD. We can export an XSD that describes what the serializerexpects and can import an XSD to product types for a specific serializer.

    XMLSerializer

    We can find XMLSerializer in the System.Xml.Serialization namespace. WCF supports this serialization from .Net 1.0. It

    is used by default with the ASP.Net webservices (ASMX).

    Usage

    We can use this serializer whenever we want to get backward compatibility with ASMX. It can also be used when integrating with non WCF Services.

    NetDataContractSerializer

    NetDataContractSerializer is analogous to .Net Remoting Formatters. It implements IFormatter and it is compatible

    with [Serializable] types. It is not recommended for service oriented design.

    Usage

    It is used when we have WCF services at both sides. It is easier when we want to migrate .Net remoting applications.

    DataContractSerializer

    DataContractSerializer is a default serializer for WCF. We need not to mention DataContractSerializer attribute above

    the service contract.

    Usage

    Used by default unless we specify otherwise. It is the best choice for code-first designs.

    Opt-In and Opt-Out used by DataContractSerializer and XMLSerializer. We will also see the difference between

    DataContractSerializer and XMLSerializer.

    Opt-Out Approach

    In this approach, members are assumed to be serialized except we mention it as NonSerialized. XMLSerializer uses this

    approach.

  • 7/28/2019 WCF Interview Questions1

    29/33

    In the above example, we set the Serializable attribute to the Author class. In other words all class members are going

    to be serialized but suppose we do not want to serialize the article member then set the NonSerialized attribute on

    article member. In this case only the firstname and lastname are serialized.

    Opt-In Approach

    In this approach we need to specify each member, which we want to serialize. For example we want to serialize the

    firstname and lastname, not an article member then we need to set the DataMember attribute to the firstname and

    lastname.

    In the above code snippet you can see that we are not applying the DataMember attribute to the Article member.

    That's why this member is not serialized.

    Now check this with svcutil.exe from the command prompt. It will generate an AuthorServiceLibrary.xsd file.

    Open the AuthorServiceLibrary.xsd file in the Notepad.

    Check the result in the Notepad file. In this file you will see only FirstName and LastName. The Article member is not

    serialized.

  • 7/28/2019 WCF Interview Questions1

    30/33

  • 7/28/2019 WCF Interview Questions1

    31/33

  • 7/28/2019 WCF Interview Questions1

    32/33

    major area for extension is the SOAP header. Chapter 7, "Building Security into SOAP," which describes WS-Security,

    provides more detail on SOAP header security extensions.

    SOAP bodycontains the message payload. This information is being sent from one application to another. It mightbe a full document such as a purchase order or contract, or it might be a description of remote-procedure call

    information, including the methods to call and parameters to those method calls.

    The simple SOAP message in Listing 1.1 shows an envelope that contains both a SOAP header and a SOAP body.

    Listing 1.1 SOAP Envelope

    1

    2004-06-22T14:00:00-5:00

    Pick up Bobby at school at 2PM

    To understand SOAP, you need to understand the different "styles" of SOAP bodies. RPC-style SOAP bodies tend to be

    simple parameters to facilitate calling a remote method. Document-style SOAP bodies tend to be rich XML documents.

    Document style, in our view, is more appropriate for B2B Web services because it is usually more optimal to have

    "chunky," coarse-grained calls across a slow network rather than the fine-grained type of RPC call that you might use

    locally or on a fast network. This is not just due to the network but also due to the cost of marshalling and

    unmarshalling the XML and performing security-related operations.

    SOAP needs to be secured. The messages it carries must be kept secret from unintended recipients. The remote

    service being called must know who is calling it and know the caller is authorized to do so. SOAP is a packaging

    mechanism for XML messages and documents. Like any package, it needs to describe important information about its

    contents, such as who it is from, how a recipient can trust that it really is the sender, what the sender is allowed to do,

    and much more. These are identity- and trust-related issues; they are the core of SOAP security discussed in detail

    later in this book.

    WSDL

    WSDL is an XML language that defines the set of operations that a Web service provides and the structure of theirrelated SOAP messages. That is, the WSDL defines what the input and output structure will be for a Web service, and

    that will define what you expect to see in the payload XML message. WSDL is how one service tells another which way

    to interact with it, where the service resides, what the service can do, and how to invoke it. WSDL directly supports

    developers and is absorbed at application development time into developer tools. WSDL's definitions of remote

    services are presented to programmer-like local objects that can be acted upon as if they were methods in classes, just

    like any of their other local objects.

    When you publish a WSDL for one of your services, you are creating a contract for how other services may interact

    with you to utilize your service. WSDL is what you publish to describe your Web service and the rules for how to work

    with it. You might think that security would also be described in WSDL because this is part of the rules for working

    with a particular Web service; however, the security options (security policy) available are richer than what you typicallysee in WSDL, so the standards are evolving toward using WS-Policy to describe a Web services security policy and

    then referring to this policy from the WSDL. Chapter 8, "Communicating Security Policy," goes into more depth on

    WS-Policy.

  • 7/28/2019 WCF Interview Questions1

    33/33

    A WSDL file has a what section, a how section, and a where section. The what section specifies the input and output

    messages. The how section defines how the messages should be packaged in the SOAP envelope and how to transfer

    it. It also defines what information should be included in the SOAP header. The where section describes a specific Web

    service implementation and ways to find its endpoint.