Вы находитесь на странице: 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 our different 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

overhead. On the other hand WCF unifies Web Services, .NET Remoting, and Enterprise Services stacks under one roof. For the same requirement that we have seen untill now, we just create one application and expose multiple end points to satisfy the requirements of multiple clients. In WCF configuration drives protocol choices, messaging formats, process allocation, etc. WCF services are loosely coupled, meaning that a WCF service is not bound to a particular protocol, encoding format, or hosting environment. Everything is configurable. Why are WCF Services are considered as loosely coupled? WCF Services are considered as loosely coupled because WCF services are not tightly bound to a particular protocol, encoding format, or hosting environment. All of these are configurable. At the time of designing WCF services, we donot have to worry about what protocol, encoding format, or hosting environment to use to expose the service. We can worry about all these at the time of deployment. What are the 3 things that a WCF Services end point must have? OR What are the ABC of a WCF service? Address - The address where the WCF Service is hosted. Binding - The binding that decides the protocol, message encoding and security to use. Binding also decides whether to use reliable messaging and transaction support. Contract - The service contract defines what service operations are available to the client for consumption. So the Address(A), Binding(B) and Contract(C) are called as the ABC of the service end point.

What is the role of WSDL in WCF? OR What is WSDL? WSDL stands for Web Service Description Language. The WCF service exposes the WSDL document for the clients, to generate proxies and the configuration file. The WSDL file provides the following information for the consumers of the WCF service. 1. Provides the information about the service contract and operations available. 2. Provides the information about all the end points exposed by the WCF service. 3. Provides the information about the messages and types that can be exchanged between the client and the WCF service. 4. WSDL also provides any information about the policies used.

What is the tool that a client application can use to generate the proxy for a WCF service? Service Utility (svcutil.exe) can be used by the clients to generate the proxy and configuration file. For the client to be

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 using interfaces 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 are using 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 received between 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.

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.

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 body elements. 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.

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. A message 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()] public class AuthorRequest { } Properties of MessageContractAttribute 1. public bool HasProtectionLevel { get; } HasProtectionLevel gets a value that indicates whether the message has a protection level.

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. 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)] public class AuthorRequest { } 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)] public class AuthorRequest { [MessageHeader()] public string 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. 5.

It returns one of the System.Net.Security.ProtectionLevel values. The default is System.Net.Security.ProtectionLevel.None. 4. public string Actor { get; set; } Actor gets or sets a URI that indicates the node at which this header is targeted. It maps to the role header attribute when SOAP 1.2 is used and the actor header attribute when SOAP 1.1 is used. It returns a URI that indicates the node at which this header is targeted. This URI maps to the role header attribute when SOAP 1.2 is used and the actor header attribute when SOAP 1.1 is used. 5. public bool MustUnderstand { get; set; } MustUnderstand specifies whether the node acting in the System.ServiceModel.MessageHeaderAttribute.Actor role must understand this header. This is mapped to the mustUnderstand SOAP header attribute. It returns true if the node acting in the System.ServiceModel.MessageHeaderAttribute.Actor role must understand this header; otherwise, false. 6. public bool Relay { get; set; }

Relay specifies whether this header is to be relayed to downstream nodes. This is mapped to the relay SOAP header attribute. It returns true if this header is to be relayed to downstream nodes; otherwise, false. MessageBodyMemberAttribute MessageBodyMemberAttribute is applied to the members of message contracts to declare the members within the message body. Properties of MessageBodyMemberAttribute Name, Namespace, ProtectionLevel and Order are the properties of MessageBodyMemberAttribute. As we are now familiar with all the properties, I am not explaining here once again. Why should we use MessageContract Suppose we are not using MessageContract in our service, by default SOAP body element contains a child wrapper element of operation name and wraps parameters. If there is no parameter then this element will be empty in the inbound (request) message. In the same way, in an outbound (response) message, if it is of type void or say nothing to return then this element will be empty. For example we create a service and set MessageContract with the property IsWrapped to false. Then there is no child element in the SOAP body. You will see a collection of MessageBodyMembers directly under the SOAP body within the MessageContract. Controlling wrapping is important when we deal with the other platforms except WCF because they might serialize their SOAP messages differently. Sample Code Consider a scenario where we create a service and in this service we have one operation contract which returns the author information. Now we want to set some authentication like AuthorId should be matched. In this case we store AuthorId in MessageHeader because it is safe. Here we create two MessageContracts, one is for the request i.e. AuthorRequest and another is for the response i.e. AuthorResponse. While creating a MessageContract consider the following two points: 1. When we pass a parameter of type MessageContract, only one parameter is used in the service operation.

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.

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.

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

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 WSDL contract 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 of IExtensibleDataObject 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

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 class PragimService : IPragimService To enable using configuration use servicedebug element as shown below

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 encoding 3. 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 want to use to a particular endpoint.

BasicHttpBinding Replacement for earlier Web Service based on ASMX (Active Server Methods) Supports: o o o wsHttpBinding Uses SOAP over HTTP and supports reliability, transactions and security over the internet. Supports: HTTP - Hypertext Transfer Protocol HTTPS - Hypertext Transfer Protocol over SSL MTOM - Message Transmission Optimization Mechanism encoding methods.

o o o

HTTP - Hypertext Transfer Protocol HTTPS - Hypertext Transfer Protocol over SSL 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 of OperationContractAttribute. Let us understand this with an example.

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 the service. 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.

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: <serviceBehavior> <behavior name="MyServiceBehavior"> <serviceThrottling maxConcurrentInstances="2147483647" maxConcurrentCalls="16" maxConcurrentSessions="10" </behavior> </serviceBehavior> The above given values are the default ones, but we can modify them after evaluating the requirements of our application What are the various WCF Instance Activation Methods available? WCF supports three different types of Instance Activation methods: a. b. c. Per Call Per Session Singleton

What are the various ways to handle concurrency in WCF? There are three different ways to handle concurrency in WCF; they are: a. b. c. Single Multiple Reentrant

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 class MyService : 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: <system.serviceModel> <services> <servicename="MyService.Service1" behaviorConfiguration="MyService.Service1"> <endpointaddress=""binding="wsHttpBinding" contract="MyService.IService1"> <identity> <dnsvalue="localhost"/> </identity> </endpoint> <endpointaddress="mex"binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behaviorname="MyService.Service1"> <serviceMetadatahttpGetEnabled="true"/> <serviceDebugincludeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> 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();

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: <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> and the service metadata behavior will be configured as follows: <serviceMetadata httpGetEnabled="true"/> 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 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 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. 2. 3. Right-click References and choose "Add Service Reference". Provide the base address of the service on "Add Service Reference" dialog box and click the "Go" button. The service will be listed below. 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.

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 SelfHosting.

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: <bindings> <wsHttpBinding> <binding name="Binding1"> <reliableSession enabled="true" ordered="true" inactivityTimeout="00:02:00" /> </binding> </wsHttpBinding> </bindings> 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?

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 information from 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 WSSecure conversations. While in the case of BasicHttpBinding, 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, an authenticated 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] public interface IService1 { [OperationContract] [FaultContract(typeof(MyFaultDetails))] int MyOperation1(); }

[DataContract] public class MyFaultDetails { [DataMember] public string ErrorDetails { get; set; } } In the implementing service public int MyOperation1() { Try{ //Do something...... }catch() { MyFaultDetails ex = new MyFaultDetails(); ex.ErrorDetails = "Specific error details here."; throw new 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. 2. Transport Level Security 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 the sender to the receiver. Integrity: This feature ensures that the receiver of the message gets the same information that the sender sent without 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.

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 p rotocol. Message level security is implemented with message data itself. Due to this, it is independent of the protocol. One of the 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 BasicHttpBinding Transport Mode? Yes Message Mode? Yes Mixed Mode? Yes

Binding WsHttpBinding WsDualHttpBinding NetTcpBinding NetNamedPipeBinding NetMsmqBinding MsmqIntegrationBinding

Transport Mode? Yes No Yes Yes Yes Yes

Message Mode? Yes Yes Yes No Yes No

Mixed Mode? Yes No Yes No No No

So what are the scenarios, advantages, and disadvantages of transport and message security? Transport Scenarios when we should be using one of them Advantages 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. Message When there are intermediate systems like one more WCF service through which message is routed, then message security is the way to go.

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 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 not affect the application. Supports a wide set of security options as it is not dependent on the protocol. We can also implement custom security. 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.

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.

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 not affect 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 value

Throttling 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 Limits the total number of calls that can currently be in progress across all service instances. The default is 16. The number of InstanceContext objects that execute at one time across a ServiceHost. The default is Int32.MaxValue. A positive integer that limits the number of sessions a ServiceHost object can accept. The default is 10.

maxConcurrentCalls

maxConcurrentInstances

maxConcurrentSessions

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 OberationalBehavior attribute used to control the instance in relation to the method call. Followings are the list Release mode available in the ReleaseInstanceMode 1. 2. 3. 4. RealeaseInstanceMode.None RealeaseInstanceMode.BeforeCall RealeaseInstanceMode.AfterCall 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.

This is designed to optimize a method such a Cleanup()

ReleaseInstanceMode.BeforeAndAfterCall This is means that it will create new instance of object before a call and deactivates the instance after call. This has combined effect of using ReleaseInstanceMode.BeforeCall and ReleaseInstanceMode.AfterCall

Explicit Deactivate You can also explicitly deactivate instance using InstanceContext object as shown below. [ServiceContract()] public interface IMyService { [OperationContract] void MyMethod(); } [ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)] public class MyService:IMyService { public void MyMethod() { //Do something OperationContext.Current.InstanceContext.ReleaseServiceInstance(); } } WCF supports three basic serializers: XMLSerializer NetDataContractSerializer DataContractSerializer WCF desterilises WCF messages into .Net objects and serializes .Net objects into WCF messages. WCF provides DataContractSerializer by default with a servicecontract. We can change this default serializer to a custom serializer like XMLSerializer. [XmlSerializerFormat] [ServiceContract] public interface IService1 { [OperationContract] void AddAuthor(Author author);

} 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 serializer expects 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.

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.

DataContractSerializer DataContractSerializer uses the Opt-In approach. This approach serializes properties as well as fields. We can serialize protected and private members also. The DataContractSerializer is faster than XMLSerializer because we don't have full control over serialization. XMLSerializer XMLSerializer uses The Opt-Out approach. This approach serializes properties only and it must be a public. It cannot understand the DataContractSerializer attribute. It will not serialize unless we apply the serializable attribute. SOAP is a specification that defines the XML format for messages, and that's about it for the required parts of the spec. If you have a well-formed XML fragment enclosed in a couple of SOAP elements, you have a SOAP message WSDL file is an XML document that describes a set of SOAP messages, and how the messages are exchanged. In other words, WSDL is to SOAP as the interface definition language (IDL) is to CORBA or COM. Since WSDL is XML, it is readable and editable, but in most cases, it is generated and consumed by software.

XML and XML Schema XML was created as a structured self-describing way to represent data that is totally independent of application, protocol, vocabulary, operating system, or even programming language. Many call XML the lingua franca of business because it is being used so broadly across all industries to portably transmit business data. The use of XML presents a broad set of security challenges. XML Schema is a way of describing the rules for a particular XML instance (also known as a document). XML can be used independently of XML Schema; however, in Web services and most business situations, the XML that you work with will be governed by an XML Schema (perhaps created by a development tool and put into your Web services WSDL file for you).

XML is the foundation of the Web services standards. All standards for describing, discovering, and invoking Web services are based on XML. SOAP and WSDL are described using XML Schema. The core security standards of XML Encryption, XML Signature, Security Assertion Markup Language (SAML), and WS-Security are XML-based and are also described by an XML Schema. XML and HTML are both text-based formats that came from the same roots. XML was initially developed to overcome the limitations of HTML, which is good at describing how things should be displayed but is poor at describing what the data is that is being displayed. XML being text-based is very important to Web services; because it is humanreadable, no tools are needed to parse and render the data, and simple text tools and editors are sufficient for its manipulation. XML documents are very wordy, and although you can easily become lost in the depth and richness of the tags, its markup format of tagged elements arranged in a hierarchical structure makes XML documents easy to comprehend. But there is a security price to pay for the open, text-based structure of XML. As you will see later, to provide data integritya guarantee that not one bit in the original document has been changedwith XML, you have to guarantee that not one charactereven whitespaceof an XML message has been changed. Verifying data integrity is particularly challenging when using XML since differences in platforms and XML parsers can result in logically equivalent documents being physically different; consequently, a process of canonicalization is necessary to make a valid comparison with the originally signed document. This is just one example of the special considerations needed when considering Web Service Security. SOAP SOAP was created as a way to transport XML from one computer to another via a number of standard transport protocols. HTTP is the most common of those transports and is, of course, the most prevalent transport used by the Web itself. SOAP itself is defined using XML, and it provides a simple, consistent, yet extensible mechanism that allows one application to send an XML message to another. SOAP is what makes application integration possible, because after XML defines the contents of a message, it is SOAP that moves the data from one place to another over the network. SOAP allows the sender and receiver of XML documents to support a common data transfer protocol. SOAP allows you to treat XML messages as requests for remote services. The SOAP model allows a clean separation between infrastructure processing and application processing of messages. Figure 1.1 shows the basic structure of a SOAP message.

Figure 1.1 The basic structure of SOAP. SOAP provides an envelope into which an XML message is placed. This envelope is just a container to hold XML data. The idea is for SOAP to create a uniform container that can then be carried by a variety of transports. SOAP prevents applications from caring about the transport; the applications see consistency in the SOAP envelope and its contents. Inside the SOAP envelope are two parts: the header and the body. SOAP headerContains information about the SOAP message (as opposed to the XML message contained in the SOAP body). This information is used to manage or secure the package. SOAP is designed to be extensible, and a

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 might be 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 <?xml version="1.0" ?> <env:Envelope xmlns:env="http://www.w3.org/2001/12/soap-envelope"> <env:Header> <n:alertcontrol xmlns:n="http://example.org/alertcontrol"> <n:priority>1</n:priority> <n:expires>2004-06-22T14:00:00-5:00</n:expires> </n:alertcontrol> </env:Header> <env:Body> <m:alert xmlns:m="http://example.org/alert"> <m:msg>Pick up Bobby at school at 2PM</m:msg> </m:alert> </env:Body> </env:Envelope> 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 their related 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 typically see 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.

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.

Вам также может понравиться