What's the Difference between WCF and Web Services?
What are the important principles of SOA (Service oriented Architecture)?
What are ends, contract, address, and bindings?
Which specifications does WCF follow?
What are the main components of WCF?
Explain how Ends, Contract, Address, and Bindings are done in WCF?
What is a service class?
What is a service contract, operation contract and Data Contract?
What are the various ways of hosting a WCF service?
How do we host a WCF service in IIS?
What are the advantages of hosting WCF Services in IIS as compared to self-hosting?
What are the major differences between services and Web services?
What is the difference WCF and Web services?
What are different bindings supported by WCF?
Which are the various programming approaches for WCF?
What is one-way operation?
Can you explain duplex contracts in WCF?
How can we host a service on two different protocols on a single server?
How can we use MSMQ bindings in WCF?
Can you explain transactions in WCF?
What different transaction isolation levels provided in WCF?
Can we do transactions using MSMQ?
Can we have two-way communications in MSMQ?
What are Volatile queues?
What are Dead letter queues?
What is a poison message?
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 integrates 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 heterogeniuos environment. We have a new client. Our new client is using .NET and he wants binary formmatted messages over TCP protocol, because interoperability is not a concern and binary formmatted messages over TCP protocol are much faster than XML SOAP formmatted 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 maintainance 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 benifits. 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? MessageParameter attribute 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 disadvanatages. Data contracts is thepreferred 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 donot 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, CorporateCustomer on SaveCorporateCustomer(Customer customer) and GetCorporateCustomer(int CustomerId) operations using ServiceKnownType attribute. In Example 3, we are associating known types, CorporateCustomer and PremiumCustomer 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 significane 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. MessageContract 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. ![]()
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 atleast 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
Are 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.
WCF Interview Questions and Answer
Q1. What is WCF?
WCF stands for Windows Communication Foundation. It is a Software development kit for developing services on Windows. WCF is introduced in .NET 3.0. in the System.ServiceModel namespace. WCF is based on basic concepts of Service oriented architecture (SOA) Q2. What is endpoint in WCF service? The endpoint is an Interface which defines how a client will communicate with the service. It consists of three main points: Address,Binding and Contract. Q3. Explain Address,Binding and contract for a WCF Service? Address:Address defines where the service resides. Binding:Binding defines how to communicate with the service. Contract:Contract defines what is done by the service. Q4. What are the various address format in WCF? a)HTTP Address Format:--> http://localhost: b)TCP Address Format:--> net.tcp://localhost: c)MSMQ Address Format:--> net.msmq://localhost: Q5. What are the types of binding available in WCF? A binding is identified by the transport it supports and the encoding it uses. Transport may be HTTP,TCP etc and encoding may be text,binary etc. The popular types of binding may be as below: a)BasicHttpBinding b)NetTcpBinding c)WSHttpBinding d)NetMsmqBinding Q6. What are the types of contract available in WCF? The main contracts are: a)Service Contract:Describes what operations the client can perform. b)Operation Contract : defines the method inside Interface of Service. c)Data Contract:Defines what data types are passed d)Message Contract:Defines wheather a service can interact directly with messages Q7. What are the various ways of hosting a WCF Service? a)IIS b)Self Hosting c)WAS (Windows Activation Service) Q8. WWhat is the proxy for WCF Service? A proxy is a class by which a service client can Interact with the service. By the use of proxy in the client application we are able to call the different methods exposed by the service Q9. How can we create Proxy for the WCF Service? We can create proxy using the tool svcutil.exe after creating the service. We can use the following command at command line. svcutil.exe *.wsdl *.xsd /language:C# /out:SampleProxy.cs /config:app.config Q10.What is the difference between WCF Service and Web Service? a)WCF Service supports both http and tcp protocol while webservice supports only http protocol. b)WCF Service is more flexible than web service. Q11.What is DataContract and ServiceContract?Explain Data represented by creating DataContract which expose the data which will be transefered /consumend from the serive to its clients. **Operations which is the functions provided by this service. To write an operation on WCF,you have to write it as an interface,This interface contains the "Signature" of the methods tagged by ServiceContract attribute,and all methods signature will be impelemtned on this interface tagged with OperationContract attribute. and to implement these serivce contract you have to create a class which implement the interface and the actual implementation will be on that class. Code Below show How to create a Service Contract:
Code:
[ServiceContract] What is WCF?
Windows
Communication Foundation (WCF) is an SDK for developing and deploying
services on Windows. WCF provides a runtime environment for services,
enabling you to expose CLR types as services, and to consume other services
as CLR types.
WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it. |
|||||||||||||||
A service is a unit
of functionality exposed to the world.
The client of a service is merely the party consuming the service. |
|||||||||||||||
Address is a way of
letting client know that where a service is located. In WCF, every service is
associated with a unique address. This contains the location of the service
and transport schemas.
WCF supports following transport schemas HTTP TCP Peer network IPC (Inter-Process Communication over named pipes) MSMQ The sample address for above transport schema may look like http://localhost:81 http://localhost:81/MyService net.tcp://localhost:82/MyService net.pipe://localhost/MyPipeService net.msmq://localhost/private/MyMsMqService net.msmq://localhost/MyMsMqService |
|||||||||||||||
In WCF, all services
expose contracts. The contract is a platform-neutral and standard way of
describing what the service does.
WCF defines four types of contracts. Service contracts Describe which operations the client can perform on the service. There are two types of Service Contracts. ServiceContract - This attribute is used to define the Interface. OperationContract - This attribute is used to define the method inside Interface.
[ServiceContract]
interface IMyContract { [OperationContract] string MyMethod( ); } class MyService : IMyContract { public string MyMethod( ) { return "Hello World"; } } Data contracts Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types. There are two types of Data Contracts. DataContract - attribute used to define the class DataMember - attribute used to define the properties.
[DataContract]
class Contact { [DataMember] public string FirstName; [DataMember] public string LastName; } If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service. Fault contracts Define which errors are raised by the service, and how the service handles and propagates errors to its clients. Message contracts Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with. |
|||||||||||||||
Every WCF services
must be hosted somewhere. There are three ways of hosting WCF services.
They are 1. IIS 2. Self Hosting 3. WAS (Windows Activation Service) For more details see http://msdn.microsoft.com/en-us/library/bb332338.aspx |
|||||||||||||||
A binding defines
how an endpoint communicates to the world. A binding defines the transport
(such as HTTP or TCP) and the encoding being used (such as text or binary). A
binding can contain binding elements that specify details like the security
mechanisms used to secure messages, or the message pattern used by an
endpoint.
WCF supports nine types of bindings. Basic binding Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services. TCP binding Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF. Peer network binding Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it. IPC binding Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding. Web Service (WS) binding Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet. Federated WS binding Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security. Duplex WS binding Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client. MSMQ binding Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls. MSMQ integration binding Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients. For WCF binding comparison, see http://www.pluralsight.com/community/blogs/aaron/archive/2007/03/22/46560.aspx |
|||||||||||||||
Every service must
have Address that defines where the service resides, Contract that defines
what the service does and a Binding that defines how to communicate with the
service. In WCF the relationship between Address, Contract and Binding is
called Endpoint.
The Endpoint is the fusion of Address, Contract and Binding. |
|||||||||||||||
WCF 3.5 provides
explicit support for RESTful communication using a new binding named
WebHttpBinding.
The below code shows how to expose a RESTful service
[ServiceContract]
interface IStock { [OperationContract] [WebGet] int GetStock(string StockId); } By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation. |
|||||||||||||||
Address format of
WCF transport schema always follow
[transport]://[machine or domain][:optional port] format. for example: HTTP Address Format http://localhost:8888 the way to read the above url is "Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting" When the port number is not specified, the default port is 80. TCP Address Format net.tcp://localhost:8888/MyService When a port number is not specified, the default port is 808: net.tcp://localhost/MyService NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine. IPC Address Format net.pipe://localhost/MyPipe We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine. MSMQ Address Format net.msmq://localhost/private/MyService net.msmq://localhost/MyService |
|||||||||||||||
The proxy is a CLR
class that exposes a single CLR interface representing the service contract.
The proxy provides the same operations as service's contract, but also has
additional methods for managing the proxy life cycle and the connection to
the service. The proxy completely encapsulates every aspect of the service:
its location, its implementation technology and runtime platform, and the
communication transport.
The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy. Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name. SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address: SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs |
|||||||||||||||
WCF Services client
configuration file contains endpoint, address, binding and contract. A sample
client config file looks like
<system.serviceModel>
<client> <endpoint name = "MyEndpoint" address = "http://localhost:8000/MyService/" binding = "wsHttpBinding" contract = "IMyContract" /> </client> </system.serviceModel> |
|||||||||||||||
Transport
reliability (such as the
one offered by TCP) offers point-to-point guaranteed delivery at the network
packet level, as well as guarantees the order of the packets. Transport
reliability is not resilient to dropping network connections and a variety of
other communication problems.
Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service. |
|||||||||||||||
Reliability can be
configured in the client config file by adding reliableSession under binding
tag.
<system.serviceModel>
<services> <service name = "MyService"> <endpoint address = "net.tcp://localhost:8888/MyService" binding = "netTcpBinding" bindingConfiguration = "ReliableCommunication" contract = "IMyContract" /> </service> </services> <bindings> <netTcpBinding> <binding name = "ReliableCommunication"> <reliableSession enabled = "true"/> </binding> </netTcpBinding> </bindings> </system.serviceModel> Reliability is supported by following bindings only NetTcpBinding WSHttpBinding WSFederationHttpBinding WSDualHttpBinding |
|||||||||||||||
The timeout property
can be set for the WCF Service client call using binding tag.
<client>
<endpoint ... binding = "wsHttpBinding" bindingConfiguration = "LongTimeout" ... /> </client> <bindings> <wsHttpBinding> <binding name = "LongTimeout" sendTimeout = "00:04:00"/> </wsHttpBinding> </bindings> If no timeout has been specified, the default is considered as 1 minute. |
|||||||||||||||
By default overload
operations (methods) are not supported in WSDL based operation. However by
using Name property of OperationContract attribute,
we can deal with operation overloading scenario.
[ServiceContract]
interface ICalculator { [OperationContract(Name = "AddInt")] int Add(int arg1,int arg2); [OperationContract(Name = "AddDouble")] double Add(double arg1,double arg2); } Notice that both method name in the above interface is same (Add), however the Name property of the OperationContract is different. In this case client proxy will have two methods with different name AddInt and AddDouble. |
|||||||||||||||
The code name of WCF
was Indigo .
WCF is a unification of .NET framework communication technologies which unites the following technologies:- NET remoting MSMQ Web services COM+ |
|||||||||||||||
The main components
of WCF are
1. Service class 2. Hosting environment 3. End point For more details read http://www.dotnetfunda.com/articles/article221.aspx#WhatarethemaincomponentsofWCF |
|||||||||||||||
There are three
major ways of hosting a WCF services
• Self-hosting the service in his own application domain. This we have already covered in the first section. The service comes in to existence when you create the object of Service Host class and the service closes when you call the Close of the Service Host class. • Host in application domain or process provided by IIS Server. • Host in Application domain and process provided by WAS (Windows Activation Service) Server. More details http://www.dotnetfunda.com/articles/article221.aspx#whatarethevariouswaysofhostingaWCFservice |
|||||||||||||||
Web services can
only be invoked by HTTP (traditional webservice with .asmx). While WCF
Service or a WCF component can be invoked by any protocol (like http, tcp
etc.) and any transport type.
Second web services are not flexible. However, WCF Services are flexible. If you make a new version of the service then you need to just expose a new end. Therefore, services are agile and which is a very practical approach looking at the current business trends. We develop WCF as contracts, interface, operations, and data contracts. As the developer we are more focused on the business logic services and need not worry about channel stack. WCF is a unified programming API for any kind of services so we create the service and use configuration information to set up the communication mechanism like HTTP/TCP/MSMQ etc For more details, read http://msdn.microsoft.com/en-us/library/aa738737.aspx |
|||||||||||||||
We Should remember
ABC.
Address --- Specifies the location of the service which will be like http://Myserver/MyService.Clients will use this location to communicate with our service. Binding --- Specifies how the two paries will communicate in term of transport and encoding and protocols Contract --- Specifies the interface between client and the server.It's a simple interface with some attribute. |
|||||||||||||||
Self hosting the
service in his own application domain. This we have already covered in the
first section. The service comes in to existence when you create the object
of ServiceHost class and the service closes when you call the Close of the
ServiceHost class.
Host in application domain or process provided by IIS Server. Host in Application domain and process provided by WAS (Windows Activation Service) Server. |
|||||||||||||||
Web Services
1.It Can be accessed only over HTTP 2.It works in stateless environment WCF WCF is flexible because its services can be hosted in different types of applications. The following lists several common scenarios for hosting WCF services: IIS WAS Self-hosting Managed Windows Service |
|||||||||||||||
Answer edited by
Webmaster
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types. WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it. (content from another post: http://www.dotnetfunda.com/interview/exam283-what-is-wcf.aspx) |
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
SOA is Service
Oriented Architecture. SOA service is the encapsulation of a high level
business concept. A SOA service is composed of three parts.
1. A service class implementing the service to be provided. 2. An environment to host the service. 3. One or more endpoints to which clients will connect. |
|||||||||||||||
ServiceBehaviour attribute
is used to specify the InstanceContextMode for the WCF Service
class (This can be used to maintained a state of the service or a client too)
There are three instance Context Mode in the WFC PerSession : This is used to create a new instance for a service and the same instance is used for all method for a particular client. (eg: State can be maintained per session by declaring a variable) PerCall : This is used to create a new instance for every call from the client whether same client or different. (eg: No state can be maintained as every time a new instance of the service is created) Single : This is used to create only one instance of the service and the same instance is used for all the client request. (eg: Global state can be maintained but this will be applicable for all clients) |
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
Major Difference is
That Web Services Use XmlSerializer But WCF Uses
DataContractSerializer which is better in Performance as Compared to XmlSerializer. Key issues with XmlSerializer to serialize .NET types to XML * Only Public fields or Properties of .NET types can be translated into XML. * Only the classes which implement IEnumerable interface. * Classes that implement the IDictionary interface, such as Hash table can not be serialized. The DataContractAttribute can be applied to the class or a strcture. DataMemberAttribute can be applied to field or a property and theses fields or properties can be either public or private. Important difference between DataContractSerializer and XMLSerializer. * A practical benefit of the design of the DataContractSerializer is better performance over Xmlserializer. * XML Serialization does not indicate the which fields or properties of the type are serialized into XML where as DataCotratSerializer Explicitly shows the which fields or properties are serialized into XML. * The DataContractSerializer can translate the HashTable into XML. |
|||||||||||||||
Fault Contract is
used to document the errors occurred in the service to client.
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
Messaging Pattern :
Messaging patterns describes how client and server should exchange the
message. There is a protocol between client and server for sending and
receiving the message. These are also called Message Exchange Pattern.
WCF supports following 3 types of Message Exchange Patterns 1. request - reply (default message exchange pattern) 2. OneWay (Simplex / datagram) 3. Duplex(CallBack) Thanks Prasham |
|||||||||||||||
.svc file is a text
file. This file is similar to our .asmx file in web services.
This file contains the details required for WCF service to run it successfully. This file contains following details : 1. Language (C# / VB) 2. Name of the service 3. Where the service code resides Example of .svc file <%@ ServiceHost Language="C#/VB" Debug="true/false" CodeBehind="Service code files path" Service="ServiceName" We can also write our service code inside but this is not the best practice. |
|||||||||||||||
The XML Information
Set defines a data model for XML. It is an abstract set of concepts such as
attributes and entities that can be used to describe a valid XML document.
According to the specification, "An XML document's information set
consists of a number of information items; the information set for any
well-formed XML document will contain at least a document information item
and several others."
|
|||||||||||||||
1.IIS
2.Self Hosting 3.WAS (Windows Activation Service) |
|||||||||||||||
DataContractSerializer
is new WCF serializer.
This is serialization engine in WCF. DataContractSerializer translate the .NET framework objects into XML and vice-versa. By default WCF uses DataContractSeriazer. |
|||||||||||||||
Message Contract :
Message Contract is the way to control the SOAP messages, sent and received by the client and server. Message Contract can be used to add and to get the custom headers in SOAP message Because of Message Contract we can customize the parameters sent using SOAP message between the server and client. Thanks Prasham |
|||||||||||||||
Fault Contracts is
the way to handle exceptions in WCF. The problem with exceptions is that
those are technology specific and therefore cannot be passed to other end
because of interoperability issue. (Means either from Client to Server or
vice-versa). There must be another way representing the exception to support
the interoperability. And here the SOAP Faults comes into the picture.
Soap faults are not specific to any particular technology and they are based on industry standards. To support SOAP Faults WCF provides FaultException class. This class has two forms: a. FaultException : to send untyped fault back to consumer b. FaultException<T>: to send typed fault data to the client WCF service also provides FaultContract attribute so that developer can specify which fault can be sent by the operation (method). This attribute can be applied to operations only. |
|||||||||||||||
a.
DataContractSerializer is the default serializer fot the WCF
b. DataContractSerializer is very fast. c. DataContractSerializer is basically for very small, simple subset of the XML infoset. d. XMLSerializer is used for complex schemas. Thanks Prasham |
|||||||||||||||
When multiple
endpoints are associated with WCF service, base address (one primary address)
is assigned to the service, and relative addresses are assigned to each
endpoint. Base address is specified in <host> element for each service.
E.g.
<configuration>
<system.servicemodel> <Services> <service name=”MyService> <host> <baseAddresses> <add baseAddress =”http://localhost:6070/MyService”> </baseAddresses> </host> </service> <services> </system.servicemodel> </configuration> Thanks Prasham |
|||||||||||||||
SOAP (Simple Object
Access Protocol), which is directly supported from WCF (Windows Communication
Foundation).
|
|||||||||||||||
ABC is the three
building blocks of WCF and they are known as
A - Address (Where): Address tells us where to find the services, like url B - Bindings (How) : Bindings tells us how to find the services or using which protocols finds the services (SOAP, HTTP, TCT etc.) C - Contacts (What): Contracts are an agreement between the consumer and the service providers that explains what parameters the service expects and what return values it gives. Hope this will be very helpful to understand three building blocks of WCF, a very frequently asked interview questions. |
|||||||||||||||
Hello,
The concurrency mode is specified using the ServiceBehavior attribute on the class that implements the service. Ex. [ServiceBehavior(ConcurrencyMode=ConcurrencyMode.Single)] Public class ServiceClass : IServiceInterface{ //Implementation Code } There are 3 possible values of ConcurrencyMode enumeration Single Reentrant Multiple Thanks Prasham |
|||||||||||||||
Hello,
WCF supports following 3 types of transactions managers: a. LightWeight b. OLE Transactions c. WS-Atomic Transactions Thanks Prasham |
|||||||||||||||
Hello,
Following bindings supports the streaming in WCF: 1. basicHttpBinding 2. netTcpBinding 3. netNamedPipeBinding Thanks Prasham |
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
We can customize the
generic datacontract names by allowing parameters. Find the Example below
[DataContract(Name = "Shape_{1}_brush_and_{0}_shape")] public class Shape< Square,RedBrush> { // Code not shown. } Here, the Data Contract Name is "Shape_RedBrush_brush_and_Square_shape” {0} – First Parameter in the generic type. {1}- Second Parameter in the generic type. |
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
Address format of
WCF transport schema always follow
[transport]://[machine or domain][:optional port] format. For example: HTTP Address Format : http://localhost:8888 The way to read the above url is "Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting" When the port number is not specified, the default port is 80. TCP Address Format net.tcp://localhost:8888/MyService When a port number is not specified, the default port is 808: net.tcp://localhost/MyService NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine. IPC Address Format net.pipe://localhost/MyPipe We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine. MSMQ Address Format net.msmq://localhost/private/MyService net.msmq://localhost/MyService |
|||||||||||||||
No, Input and return
parameter should be same as Message contract if we want to use message
contract in a operation contract.
|
|||||||||||||||
Asynchronous
messaging describes a way of communications that takes place between two
applications or systems, where the system places a message in a message queue
and does not need to wait for a reply to continue processing.
|
|||||||||||||||
Its the ability to
re-use existing software assets whenever possible and to expose the
functionality of these assets as a set of services.
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
WCF uses the class
to convert objects into a stream of data suitable for transmitting over the
network (this process is known as Serialization). It also uses them to
convert a stream of data received from the network back into objects
(De-Serialization).
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
The attribute "httpGetEnabled" is
essential because we want other applications to be able to locate the
metadata of this service that we are hosting.
<serviceMetadata
httpGetEnabled="true" />
Without the metadata, client applications can't generate the proxy and thus won't be able to use the service. |
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
Automatic Activation
means that the service is not necessary to be running in advance. When any
message is received by the service it then launches and fulfills the request.
But in case of self hosting the service should always be running.
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
No, we cannot
propagate CLR Exceptions across service boundaries.
If you want to propagate exception details to the clients then it can be done through "FaultContract " attribute. This way a custom exception is being passed to the client. |
|||||||||||||||
The service model
returns a generic SOAP fault to the client which does not include any
exception specific details by default. However, an exception details in SOAP
faults can be included 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.
IncludeExceptionDetailsInFaults can be enabled in the web.config file :-
<behaviors>
<serviceBehaviors> <behavior name="ServiceGatewayBehavior"> <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> <serviceMetadata httpGetEnabled="true"/> <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> <serviceDebug includeExceptionDetailInFaults="true"/> </behavior> </serviceBehaviors> </behaviors> |
|||||||||||||||
Yes, SOAP faults are
inter-operable as they are expressed to clients in XML form.
.Net exception classes are not good to be used in SOAP faults. Instead we should define our own DataContract class and then use it in a FaultContract.
public interface
ICalculator
{ [OperationContract] [FaultContract(typeof(MathFault))] int Divide(int n1, int n2); }
[DataContract]
public class MathFault { [DataMember] private string operation { get; set; } [DataMember] private string problemType { get; set; } }
public int
Divide(int n1, int n2)
{ try { return n1 / n2; } catch (DivideByZeroException) { MathFault objMath = new MathFault(); objMath.operation = "division"; objMath.problemType = "divide by zero"; throw new FaultException<MathFault>(objMath); } } |
|||||||||||||||
It is a class by
which a service client can interact with the service. The client will make an
object of the proxy class and by the help of it will call different methods
exposed by the service.
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
Simplex - Also
known as one way communication. Source will send a message to the target, but
target will not respond to the message.
Request/Replay - It is two way communications, source send message to the target, target will resend the response message to the source. But in this scenario at a time only one can send a message (that is), either source or destination. Duplex -Also known as two way communication, both source and target can send and receive message simultaneously. |
|||||||||||||||
[MessageContract]
public class EmployeeDetails { [MessageHeader] public int ID; [MessageBodyMember] public string First_Name; [MessageBodyMember] public string Last_Name; } Message contract can be applied to type using MessageContract attribute as shown above. We can add custom header and custom body by usingMessageHeader and MessageBodyMember attribute respectively. When EmployeeDetails type in the service operation is used as parameter then WCF will add an extra header call 'ID' to the SOAP envelope. It also add First_Name, Last_Name as an extra member to the SOAP Body. |
|||||||||||||||
When we need a
higher level of control over the message, such as sending custom SOAP header,
then we can use MessageContract instead of DataContract .
But in general cases, most of the messaging needs can be fulfilled by DataContracts.
|
|||||||||||||||
(1) Inter-operability
with applications built on differnet technologies.
(2) Unification of the original Dotnet Framework communication Technologies. (3) Support for Service Oriented Architecture (SOA). |
|||||||||||||||
Web Service (that
is), ASMX will be the most likely way to achieve cross-vender
inter-operability.
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
The three components
that a WCF must implement are :-
(1) Service Class = This can be implementated in any dotnet language. It implements one or more methods. (2) Host Process = A process in which the service will run. (3) End-Points = One or more end-points are provided that allow the clients to access the service. |
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
If you do not
specify "[OperationContract] " in any of the methods in your
interface then you will get the following error :-
IService1' has zero
operations; a contract must have at least one operation
Here, Iservice is the name of my Interface. you can have your own name. So, it is mandatory to label "[OperationContract] " attribute to at least one method while declaring your interface methods or ServiceContract. |
|||||||||||||||
Yes, a struct can be
used as a DataContract. For example :-
[DataContract]
struct EmployeeInfo { [DataMember] public int id; [DataMember] public string name; [DataMember] public DateTime joining_date; } |
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
No, SOAP envelope is
not created in WebHttpBinding . The information is trasmitted
through HTTP or HTTPS.
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
NetNamedPipesBinding binding
is used.
|
|||||||||||||||
ServiceHost s = new
ServiceHost(typeof(EmployeeReservations));
s.AddEndpoint(typeof(EmployeeReservations), new BasicHttpBinding(), "http://www.google.com/employee/emp.svc"); EmployeeReservations is the name of the contract. http://www.google.com/employee/emp.svc is the address of the web service. |
|||||||||||||||
Even though defining
endpoints programmatically is possible, the most common approach
today is to use a configuration file associated with the service. Endpoint definitions embedded in code are difficult to change when a service is deployed, yet some endpoint characteristics, such as the address, are very likely to differ in different deployments. Defining endpoints in config files makes them easier to change, since changes don?t require modifying and recompiling the source code for the service class. Thanks an Regards |
|||||||||||||||
Configuration
information for all services implemented by a WCF-based application is
contained within the system.serviceModel element. This element contains a services element that can itself contain one or more service elements. |
|||||||||||||||
To encrypt sensitive
data in WCF configuration file, use aspnet_regiis.exe tool.
Example: If you want to encrypt Connection String section of WCF config file, use -pe that means provider encryption .
aspnet_regiis -pe
"connectionStrings" -app "/MachineDPAPI"
-prov "DataProtectionConfigurationProvider" -pe means provider encryption of configuration section. -app means your application's virtual path. -prov means provider name For more info: http://msdn.microsoft.com/en-us/library/k6h9cz8h(VS.80).aspx |
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
WCF Data Services are
used when you want to expose your data model and associated logic through a
RESTful interface. It includes a full implementation of theOpen Data (OData) Protocol
for .NET to make this process very easy.
WCF Data Services was originally released as ‘ADO.NET Data Services’ with the release of .NET Framework 3.5. |
|||||||||||||||
WCF One Way Contract
are methods/operations which are invoked on the service by the client or the
server in which either of them do not expect a reply back. For example :-
If a client invokes a method on the service then it will not expect a reply back from the service. |
|||||||||||||||
One way contract is
used to ensure that the WCF client does not go in a blocking mode .
If your WCF operation contracts are returning nothing and they are doing some
heavy process then it is better to use one way contract.
|
|||||||||||||||
WCF one way contract
is implemented via "IsOneWay = true/false" attribute.
For example :-
[ServiceContract]
interface IMyContract { [OperationContract(IsOneWay = true)] void MyMethod( ); } |
|||||||||||||||
NOTE: This is
objective type question, Please click question title for correct answer.
|
|||||||||||||||
No, one-way
operations cannot return values and any exception thrown on the service side
will not make its way to the client. The client will never know whether there
was an error or not !
|
|||||||||||||||
No, there should be
no reply associated with a one-way operation. In the above an integer value
is returned even though the IsOneWay property is true !
|
|||||||||||||||
[ServiceContract(SessionMode
= SessionMode.Required)]
interface IService { [OperationContract(IsOneWay = true)] void Method1(); } If the client issues a one-way call and then closes the proxy while the method executes, the client will still be blocked until the operation completes. Please note that the above is a bad design because clients are never meant to be blocked when using one way contract. Thansks and Regards |
|||||||||||||||
In Duplex contract,
clients and servers can communicate with each other independently.
Duplex contracts consists of two one-way contracts so that parallel communication is achieved. |
|||||||||||||||
Three message
patterns available in WCF are :-
(1) One Way Contract (2) Duplex Contract (3) Request-Reply Contract |
|||||||||||||||
Duplex Contracts are
needed when the service queries the client for some additional information or
the service wants to explicitly raise events on the client.
|
|||||||||||||||
[ServiceContract(Namespace = "http://www.Microsoft.com", SessionMode = SessionMode.Required, CallbackContract = typeof(IDuplexCallBack) )] public interface IService1 { [OperationContract(IsOneWay = true)] void getData(); } public interface IDuplexCallBack { [OperationContract(IsOneWay = true)] void filterData(DataSet Output); } In the above code, getData() is a method which will be called by the client on the Service. This getdata() is implemented in the server side. filterData() is a method which will be called by the server on the Client. This method is implemented in the client side. CallbackContract is the name of the contract which will be called by the server on the client to raise an event or to get some information from the client. |
|||||||||||||||
[DataContract]
public class A { [DataMember] public MyCustomType AValue1{ get; set; } [DataMember] public MyCustomType AValue2 { get; set; } } [DataContract] public class B: A { [DataMember] public double BValue1{ get; set; } [DataMember] public double BValue2 { get; set; } } the metadata fails to load when testing the services. What needs to be done to load both super and sub class. We must add KnownType Attribute. [DataContract] [KnownType(typeof(B))] public class A { [DataMember] public string Value { get; set; } } [DataContract] public class B : A { [DataMember] public string OtherValue { get; set; } } |
|||||||||||||||
WCF Metadata can be
accessed in two ways :-
(1) WSDL document can be generated which represents the endpoints and protocols (2) Or the ServiceHost can expose a metadata exchange endpoint to access metadata at runtime |
|||||||||||||||
Reliable messaging is
concerned with ensuring that messages are delivered exactly once.
Reliable session provides a context for sending and receiving a series of reliable messages. reliable sessions have a dependency on reliable messaging. You have to use reliable messaging to provide an end-to-end reliable session between a client application and a service. So finally, both are different but related concepts |
|||||||||||||||
It is a set of
extensions to the Windows OS aimed at making it easier for developers to
build faster, scalable, and more-easily managed services.
It provides a distributed in-memory caching service and replication technology that helps developers improve the speed and availability of .NET Web applications and WCF services. If you are hosting WCF services by using IIS or WAS in a production environment, you might want to consider implementing Windows Server AppFabric. You can use use AppFabric in place of Memcached because AppFabric provides more feature than Memcached |
|||||||||||||||
Some points are as
under
1) WCF is concerned with technical aspects of communication between servers across tiers and message data management whereas RIA Web Services delegates this functionality to WCF. 2) WCF is a generic service that could be used in Windows Forms for example whereas RIA Web Services is focused on Silverlight and ASP.NET clients 3) WCF does not generate source code to address class business logic such as validation that may need to be shared across tiers like RIA Web Services does. 4) The RIA Services can either exist on top of WCF or replace the WCF layer with RIA Services using alternatice data source e.g. an ORM layer(EF/NHibernate etc.) 5) RIA Services allow serializing LINQ queries between the client and server. |
|||||||||||||||
Role-based :
Map users to roles and check whether a role can perform the requested
operation.
• Identity-based : Authorize users based on their identity. • Claims-based : Grant or deny access to the operation or resources based on the client’s claims. • Resource-based : Protect resources using access control lists (ACLs) |
|||||||||||||||
WCF is Windows
Communication Foundation that uses message based communication. Messages will
be sent between endpoints generated by Client or Service.
It ia an advanced version of the below technologies as these require specialized knowledge and service to implement. 1. ASP .NET Web services(.asmx) 2. Remoting 3. MSMQ (Microsoft Message Queue) 4. Enterprise Services WCF simplifies developer's task by unifying the strength of each .NET technology for network distributed services and applications |
|||||||||||||||
The benefits include
the following
1. Transactional support 2. Asynchronous one-way messaging 3. Interoperability 4. Independent versioning 5. Platform Consolidation |
|||||||||||||||
WCF services
effectively communicates with the clients through these principles.
1. Explicit boundaries WCF services function using the defined interfaces to identify the communications between server and client that flow outside the boundaries of the service 2. Independent services WCF services are deployed and managed independently and each service interaction is independent of other interactions. They are independent of deployment, installation and version issues. 3. Schema and contract based communication WCF services communicate with clients by providing only the schema of the message and not its implementation classes. The service implementation can be changed if required without impacting the clients 4. Policy based compatibility Compatibility between WCF services and clients at runtime is determined using published policies. Policies help separate the description of the service fro its implementation details. |
|||||||||||||||
SOA based WCF
architecture has four layers.
1. Contracts It describe the WCF message system. This is achieved by three contracts with policies and bindings. 1. Service Contract - Describes the method signature of the service using C# or VB 2. Data Contract - Enables .NET types to be in XML 3. Message Contract - Defines the structure os the SOAP message exchanged between the service and client 4. Policies and Bindings - Defines the security level required by the clients 2. Service Runtime This includes the behaviors that occur when service is running. 3. Messaging This layer contains the channels that process messages and operate on messages and message headers 4. Hosting Describes the ways in which WCF service can be hosted. |
|||||||||||||||
The following
behaviors are included in the WCF Service Runtime layer..
1. Throttling behavior Throttling behavior provides the options to limit how many instances or sessions are created at the application level. 2. Error behavior By implementing IErrorHandler interface WCF allows an implementer to control the fault message returned to the caller and also it performs custom error processing such as logging 3. Metadata behavior Through the metadata behavior we can publish metadata of the service by configuring an endpoint to expose the IMetadataExchange contract as an implementation of a WS-MetadataExchange (MEX) protocol. By default it is disabled. 4. Instance behavior This behavior specifies how many instance of the service has to be created while running WCF. 5. Transaction behavior This is used to enables the rollback of transacted operations if a failure occurs. 6. Dispatch behavior This behavior controls how a message is processed by the WCF Infrastructure. 7. Concurrency behavior Concurrency behavior measures how many tasks can be performed simultaneously 9. Parameter Filtering This demonstrates how to validate the parameters passed to a method before it is invoked. |
|||||||||||||||
A duplex service
contract refers to exchange of messages in which both server or client
endpoints can send messages to the other independently.
A duplex service can send message back to the client endpoint providing event like behavior. |
|||||||||||||||
A pair of interfaces
is required to create a duplex contract.
1. Service Contract interface - Describes the operations that a client can invoke. 2. Callback Contract interface - Describes the operations that service can call on client. The service contract should specify a callback contract in the System.ServiceModel.ServiceContractAttribute.CallbackContract property. |
|||||||||||||||
[ServiceContract(SessionMode=SessionMode.Required,
CallbackContract=typeof(IRespondBackCallback))] public interface ICalculatorDuplex { [OperationContract(IsOneWay = true)] void FunctionClientCanCall(); } public interface IRespondBackCallback { [OperationContract(IsOneWay = true)] void FunctionServiceCanCall(double result); } |
|||||||||||||||
The Messaging layer
contains channels that process messages and operate on messages and message
headers. The messaging layer has eight channels which defines the possible
formats and data exchange patterns.
The eight channels are divided into two categories. 1. Transport Channels These channels helps reads and write messages from the network. 1. WS Security Channel 2. WS Reliable MessagingChannel 3. Encoders:Binary/ MTOM/ Text/ XML 2. Protocol Channels These channels implement message processing protocols. 1. HTTP Channel 2. TCP Channel 3. TransitionFlow Channel 4. NamedPipe Channel 5. MSMQ Channel |
|||||||||||||||
Throttling behavior
of the WCF service holds the configuration for three limitations that control
the amount of resources that your service hosting can allocate to deal with
the client request. Thus it enables to
1. Manages resource Usage 2. Balances performance load |
|||||||||||||||
Throttling behavior
is specified by the following three parameters.
1. MaxConcurrentCalls - Total no of concurrent calls service will accept 2. MaxConcurrentSessions - Total no of sessionful channels service will accept 3. MaxConcurrentInstances - Total no of service instances will be created for servicing requests. It can be specifed either through code or configuration file. It requires the "System.SystemModel.Behavior" namespace to be included. |
|||||||||||||||
Metadata Export is
the process of describing the service endpoints and projecting them into a
parallel, standardized representation that clients can use to understand how
to use the service.
|
|||||||||||||||
WCF services publish
its metadata by exposing one or more metadata endpoints. Publishing service
metadata makes service metadata available using standardized protocols, such
as MEX and HTTP/GET requests.
Metadata endpoints are the same as other service endpoints and have an address, a binding, and a contract. You can add metadata endpoints to a service host in configuration or in code. |
|||||||||||||||
The Data contract is
not inherited, so any derived class, would have to be explicitly declared as
having a Data contract attribute as well.
|
|||||||||||||||
The best way to
handle this would be to design a Message contract that
accepts these authentication tokens in the header of the message. |
|||||||||||||||
The address for an
endpoint is a unique URL that identifies the
location of the service. The address should follow the Web Service Addressing (WS-Addressing) standard, and they are :- (1) Scheme - This is typically “http” followed by a colon. (2) Machine - Identifies the machine name, which can be a public URL such as “www.google.com" or a local identifier such as “localhost”. (3) Port - The optional port number, preceded by a colon. (4) Path - The path used to locate the service files. Typically, this is just the service name, but the path can consist of more than one level when a service resides in a directory structure. |
|||||||||||||||
An address can vary,
depending on whether it is hosted by Microsoft Internet Information Services
(IIS) on a public network or hosted locally on an internal network computer.
It can also vary, depending on the protocol the binding uses. For example,
all the following could be valid addresses:
(1) http://www.google.com/MyService/ (2) http://localhost:9800/Service1/MyService/ (3) net.tcp://localhost:9801/MyService/ |
|||||||||||||||
For serialization,
WCF uses the System.Runtime.Serialization namespace for
serialization.
Web service(i.e), ASMX uses System.Xml.serialization namespace. |
|||||||||||||||
(1) ServiceContracts
maps to WSDL
(2) DataContracts maps to XSD (3) MessageContracts maps to SOAP |
|||||||||||||||
WCF Test Client is a GUI
tool which enables us to enter parameters, invoke services with these
parameters and view the responses returned by services.
After you create a new WCF service project and press F5 to start the debugger, the WCF Service Host begins to host the service in your project. Then, WCF Test Client opens and displays a list of service endpoints defined in the configuration file. You can test the parameters and invoke the service, and repeat this process to continuously test and validate your service. |
|||||||||||||||
[ServiceContract]
public interface IService1 { [OperationContract] void Employee(string value); } In the above case, the response message is still being sent back to the client. The difference is it sends an empty SOAP body. So, returning void doesn't mean it will not return anything to the Client ! |
|||||||||||||||
It is dangerous to
send a oneway message since there is no assurance that the
operation is processed or not.
|
|||||||||||||||
(1) Threading
problems can occur if either of the Callback channels are not empty.
(2) If the client and service has a long running work then this pattern doesn't scale very well. It can block the client or the service until the process is completes ! (3) It requires a connection back to the client. And there may be a chance to not connect back due to firewall and Network Address Translation problems. Note :- It is always better to use Request / Response MEP rather than using Duplex method. |
WCF
Subscribe to:
Posts (Atom)
No comments:
Post a Comment