3. SOA can be simply defined as an architectural
concept or style that uses a set of “loosely
coupled services” to achieve the desired
functionality.
4. Boundaries are Explicit.
Services are Autonomous
Services share schema and contract, not class
Service compatibility is determined based on
policy
5. Services are secure
Services leave the system in a consistent state
Services are thread-safe
Services are reliable
7. WCF is a programming model that enables
developers to build service solutions that are
reliable and secure, and even transacted.
WCF simplifies development of unified,
simplified and manageable distributed
systems
10. Programming model type
1. You can use the object model programmatically.
2. You can use configuration files.
3. You can use declarative programming
(attributes).
The order in which settings are applied is as
follows:
1. Attributes are applied.
2. The configuration is applied.
3. The code runs.
12. What do I send?
Where do I send it?
How should I send it?
Contract
Address
Binding ServiceClient
Endpoint Endpoint
a network address
indicates where the service
is located.
specifies how a client can
communicate with the
endpoint
identifies what operations
are available to the
clients
13. WCF Service Library
◦ WCF Test Client
◦ WCF Configuration Editor
◦ Output is dll
◦ Has app.config file
Website Project Template
◦ Has web.config
◦ Used over asp.net webservice
◦ Has a .svc file
15. It contains information about what a service
does and the type of information it will make
available.
There are three types of contracts:
Data Contract
Message Contract
Service Contract
Operation Contact
17. The service contract expresses the “methods”
that are exposed to the outside world.
using System.ServiceModel;
namespace MyFirstWCF
{
[ServiceContract(Namespace =
"http://Ebusiness30/WCF")]
interface IService
{
[OperationContract]
Operation1( );
[OperationContract]
Operation2( );
}
}
class MyService :
IMyContract
{
public string
MyMethod( )
{
return "Hello WCF";
}
}
18. Define the custom types that you will use as a
parameter or return in your operation
contract
[DataContract(Namespace=" Ebusiness30WCF")]
public class Customer
{
[DataMember(Name=“CustomerName")]
public string Name;
[DataMember(Name=“NID")]
public int id;
[DataMember(Name=“Type")]
private string type;
}
19. use message contracts to control how
properties of your types map to the SOAP
headers and SOAP body
[MessageContract(Namespace=" Ebusiness30/WCF")]
public class Customer
{
[MessageBody(Name=“CustomerName")]
public string Name;
[MessageBody(Name=“NID")]
public int id;
[MessageHeader(Name=“Type")]
private string type;
}
22. Bindings are the mechanism by which communication
details are specified to make connecting to a service’s WCF
endpoint possible
A binding defines how you can communicate with the
service
The binding controls the following:
◦ The transport (HTTP, MSMQ, Named Pipes, TCP)
◦ The channels (one-way, duplex, request-reply)
◦ The encoding (XML, binary,MTOM)
◦ The supported WS-* protocols (WS-Security, WS-Federation, WS-
reliability, WS-Transactions)
Using bindings is a two-step process, as follows
◦ Select the binding from the predefined list of WCF bindings that
you will use for a particular endpoint.
◦ Create an endpoint that utilizes the binding that you have selected
or created.
23. Binding Name
Transport
Encoding
Interop
Security
Session
Transaction
Duplex
Streaming
BasicHttpBinding HTTP/S Text.MTOM BP 1.1 T X
WsHttpBinding HTTP/S Text.MTOM WS T | S X X X
WsDualHttpBinding HTTP/S Text.MTOM WS T | S X X X X
NetTcpBinding TCP Binary .NET T | S X X X X
NetNamedPipesBinding IPC Binary .NET T | S X X X X
NetMsmqBinding MSMQ Binary .NET T | S X
NetPeerTcpBinding P2P Binary .NET T | S X
MsmqIntegrationBinding MSMQ Binary MSMQ T X
T = Transport Security | S = WS-Security
It specifies the communication details required to connect to the
endpoint.
26. An address basically declares “here I am” to the
outside world.
Example
http://localhost/myservice/
protocol domain Service path
27. HTTP
◦ http://domain [:port]/path
HTTPS
◦ https://domain[:port]/path
TCP
◦ net.tcp://domain/path
MSMQ
◦ net.msmq://domain/queue name
Named pipe no port not cross-machine
◦ net.pipe://localhost/path
IIS
◦ http://domain[:port]/virtual directory[.svc file]
28. Base address
◦ enables you to host multiple endpoints under the same
base address
◦ [transport]://[host name][:optional port]/[optional path]
Endpoint address
◦ Endpoint address is where the service is actually listening.
Mex address
◦ Used to obtain metadata of the service
◦ [transport]://[host name][:optional port]/[optional path]
MyServiceMex
32. IIS 6 (ASPNET_WP.EXE / W3wp.exe)
◦ Activation on demand upon client request.
◦ Only supports HTTP/S transport.
Self Hosting
◦ Can be any managed application, i.e. Console or
WinForms application.
◦ Low-level but flexible.
Windows Activation Service (WAS)
◦ Supports all transports.
◦ Will ship with IIS 7 on Vista and Longhorn Server.
Managed Windows Services (NT Services)
33. 33
class HelloHost
{
static void Main(string[] args)
{
ServiceHost host =
new ServiceHost(typeof(HelloService));
host.Open();
// Wait until done accepting connections
Console.ReadLine();
host.Close();
}
}
<%@ Service Language=“C#” Class=“HelloService” %>
http://localhost/HelloService/HelloService.svc
Self-host
WAS/IIS-host
35. Create a service host
Open the host to allow calls in
Close the host to gracefully exit
◦ Calls in progress complete.
◦ Host refuse any further calls even if host process is still
running.
public static void Main ()
{
Uri baseAddress = new Uri ("http://localhost:8000");
using (ServiceHost serviceHost =
new ServiceHost (typeof(MyService), baseAddress))
{
serviceHost.Open ();
// The service can now be accessed.
Console.WriteLine ("Press <ENTER> to terminate service.");
Console.ReadLine ();
}
}
39. Client uses a proxy to consume the service
The proxy
◦ Is CLR interface and class representing the service.
◦ Provides the same operations as service.
◦ Has additional methods for managing the proxy and the
connection.
Generate the proxy
◦ SvcUtil.exe <Base Address> [/out:<file>] [/config:<file>]
◦ When hosted in IIS/WAS
SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs
◦ When self-hosting
SvcUtil http://localhost:8000/MyService/ /out:Proxy.cs
SvcUtil net.tcp://localhost:8001/ /out:Proxy.cs
SvcUtil net.pipe://localhost/MyPipe/ /out:Proxy.cs
◦ HTTP transport
Add Service Reference to the project in VS 2005
41. Client needs to instantiate proxy object
◦ Provide the constructor with endpoint
◦ Endpoint section name from config file
Use service methods
Close proxy instance
using (MyContractProxy proxy = new MyContractProxy
("MyEndpoint") )
{
proxy.MyMethod ();
}
42. No Proxy Client
◦ Work directly with channel
ChannelFactory<IMyContract> factory =
new ChannelFactory<IMyContract> ("MyEndpoint");
IMyContract channel = factory.CreateChannel();
channel.MyMethod ();
factory.Close ();
Need to know the contract interface
upfront
44. in this section you will learn how
1. Handle exceptions in the client applications and
services
2. Specify the exception that a WCF can raise
3. Propagate information about exceptions form
service to client
4. Learn about services state
5. Recover service that has failed
6. Detect unrecognized messages sent to the service
by the client application
45. Why SOAP fault and not CLR exception
◦ Simply , CLR exceptions are specific to the.NET
framework, java client application would not
understand the format of a CLR exception raised by
a WCF service
So, Interoperable services built by using the
WCF should convert .NET Framework
exceptions into SOAP faults and follow the
SOAP specification for reporting these faults
to client applications.
47. ServiceMthod{
Try{
service logic that may
generate an exception
}
catch(Exception e )
{
throw new
FaultException(
e.message,
new
FaultCode(“FaultName”)
}
Catching Client side
SeviceCall{
Try{
calling serviceMethod()
}
catch(FaultException e )
{
print e.code.name,
print e.Reason
}
48. Strongly typed exception
◦ A SOAP fault message that contains a sufficient
detail about the exception in order to enable the
user, or an administrator, to understand the reason
for the exception and if possible take any necessary
corrective action.
◦ Use FaultContract attributes in a service contract
◦ Note you cannot use it with one way operations
49.
50. Configure the WCF service to send details
of Unanticipated exceptions
◦ Configuration file
In the <serviceBehaviors> section of the App.config file add this tag in
the <behavior> section
Setting the includeExceptionDetailInFaults attribute to true causes WCF
to transmit the full details of exceptions when it generates SOAP faults
for unanticipated errors.
◦ Programmatically
<serviceDebug includeExceptionDetailInFaults="true"/>
[ServiceBehavior(IncludeExceptionDetailInFaults=true)]
public class ServiceImpl : IService {}
51. May I decide to make it a self study topic or
research that must be given in lab
Or give them a hint about it
Or decide to give it with no examples
Or decide to give it with examples
Summary if I didn’t give it I won’t be upset s
52. when a ServiceHost object enters the Faulted state it triggers Faulted
event . You should subscribe to this event, and provide a method
that attempts to determine the cause, and then abort and restart the
service.// ServiceHost object for hosting a WCF service
ServiceHost HelloworldServiceHost;
HelloworldServiceHost = new ServiceHost(…);
// Subscribe to the Faulted event of the productsServiceHost object
HelloworldServiceHost.Faulted += new
EventHandler(faultHandler);
// FaultHandler method Runs when productsServiceHost enters the
Faulted state
void faultHandler(object sender, EventArgs e)
{
// Examine the properties of the HelloworldServiceHost
object
// and log the reasons for the fault
// Abort the service
HelloWorldServiceHost.Abort();
// Recreate the ServiceHost object
HelloWorldServiceHost = new ServiceHost(…);
// Start the service
HelloWorldServiceHost.Open();
53. If a client application sends a message specifying an action that
the service does not recognize, the service host application
raises the UnknownMessageReceived event. The host application
can catch this event and record the unrecognized message, like
this// ServiceHost object for hosting a WCF service
ServiceHost HelloWorldServiceHost;
HelloWorldServiceHost = new ServiceHost(…);
// Subscribe to the UnknownMessageReceived event of the
HelloWorldServiceHost object
HelloWorldServiceHost.UnknownMessageReceived += new
EventHandler<UnknownMessageReceivedEventArgs>(unknownMessag
e);
// UnknownMessageReceived event handler
void unknownMessage(object sender,
UnknownMessageReceivedEventArgs e)
{
// Log the unknown message
// Display a message to the administrator
MessageBox.Show("A client attempted to send the message
" +
e.Message.Headers.Action);
One of the biggest IT topics today has to be the concept of Service-Oriented Architecture (SOA).
When you want to understand the meaning of something, you usually go to a place that defines it, such as a dictionary. In this case, we turn to the W3C to understand the definition of SOA.
The W3C defines Service-Oriented Architecture as: A set of components which can be invoked and whose interface descriptions can be discovered and published.
Service orientation is not a technology but instead is a design concept
Service orientation uses the best practices for building today’s distributed applications
Tenet 1: Boundaries are Explicit. Based on the underlying concept of encapsulation, this tenet specifies the publishing and consumption of functionality as sets of services that abstract their underlying implementation. With WCF, the attribute-based programming enables developers to explicitly define external service contracts. Without explicitly defining these, nothing within the class will be exposed publicly. In other words, WCF provides an opt-in model for explicitly defining service boundaries.
Tenet 2: Services are Autonomous. Autonomy means we design the system to support the inevitable evolution of the service’s implementation over time. As we build our services, we need to assume that their internal implementation will evolve (be versioned) over time and that our services as well as the services on which we depend could change location at (almost) any time.
Tenet 3: Services share schema and contract, not class. For those of you who are familiar with ASMX - this is exactly how ASMX works: The service publishes a contract that clients use to generate their own code to call the service. No types are shared between service and its clients by default. In addition, neither Service requires knowledge of each others’ internal workings in order to exchange data – they only need the published schemas & contracts
Tenet 4: Service compatibility is determined based on policy. The services communicate through dynamically negotiated communications channels that support the necessary semantics (security, reliability, etc). Service policy statements created automatically based on configuration, class attributes, and method signatures. Client channels automatically configured via retrieved service policy. By “name” means that we reference a well known name in Policy that represents a whole specification of behavior that needs to be used when talking to this endpoint.
Services are secure
A service and its clients must use secure communication. At the very least, the transfer of the message from the client to the service must be secured, and the clients must have a way of authenticating the service. The clients may also provide their credentials in the message so that the service can authenticate and authorize them.
Services leave the system in a consistent state
Conditions such as partially succeeding in executing the client's request are forbidden. All resources the service accesses must be consistent after the client's call. A service must not have any leftovers as a result of an error, such as only partially affecting the system state. The service should not require the help of its clients to recover the system back to a consistent state after an error.
Services are thread-safe
The service must be designed so that it can sustain concurrent access from multiple clients. The service should also be able to handle causality or logical thread reentrancy.
Services are reliable
If the client calls a service, the client will always know in a deterministic manner if the message was received by the service. The messages should also be processed in the order they were sent, not in the order they were received.
Services are robust
The service isolates its faults, preventing them from taking down itself or other services. The service should not require the clients to alter their behavior according to the type of error the service encountered. This helps to decouple the clients from the service on the error-handling dimension
An Address is a network address indicates where the service is located.
A Binding specifies how a client can communicate with the endpoint including transport protocol, encoding, and security requirements.
A Contract identifies what operations are available to the clients
Data Contract
A data contract explicitly stipulates the data that will be exchanged by the service
Message Contract
A message contract lets you customize the type formatting of parameters in SOAP messages
Service Contract
A service contract is what informs the clients and the rest of the outside world what the endpoint has to offer and communicate
16
ServiceContract Parameters
CallbackContract: Gets or sets the type of callback contract. This is useful when using the duplex messaging exchange pattern.
ConfigurationName: Defines the name as used in the configuration file to store the related configuration settings.
Name: Gets or sets the name for the <portType> element in WSDL. The default value is the name of the .NET interface.
Namespace: Gets or sets the namespace for the <portType> element in WSDL. The default value is the namespace of the .NET interface.
HasProtectionLevel: Defines a (read-only) value that indicates the protection level of the service. At the operation level, it is possible to define that the messages of the operation must be encrypted, signed, or both.
ProtectionLevel: Defines the protection level that the binding must support.
SessionMode: Gets or sets a value that defines whether the contract requires the WCF binding associated with the contract to use channel sessions. SessionMode is an enumeration with possible values of allowed, notallowed, and required. The default value is allowed.
OperationContract parameters
Name: Specifies the name of the operation. The default is the name of the operation.
Action: Defines the (WS-Addressing) action of the request message.
AsyncPattern: Indicates that the operation is implemented asynchronously by using a Begin/End method pair.
IsInitiating: Defines a value that indicates whether the method implements an operation that can initiate a session on the server.
IsOneWay: Defines a value that indicates whether an operation returns a reply message.
IsTerminating: Defines a value that indicates whether the operation causes the server to close the session after the reply message is sent.
ProtectionLevel: Defines a value that indicates the protection level of the operation. You can define that the messages of the operation must be encrypted, signed, or both.
ReplyAction: Defines the value of the SOAP action for the reply message of the operation.
DataContract parameters
Name: Defines the name for the data contract, which will also be the name in the XML schema (XSD, WSDL). The default value is the name you defined in .NET.
Namespace: Defines the namespace for the data contract. Use this property to specify a particular namespace if your type must return data that complies with a specific data contract or XML schema.
DataMember parameters
Name: Defines the name for the data contract, which will also be the name in an XML schema (XSD, WSDL). The default value is the name you defined in .NET.
Namespace: Defines the namespace for the data contract. Use this property to specify a particular namespace if your type must return data that complies with a specific data contract or XML schema.
IsRequired: Gets or sets a value that instructs the serialization engine that the member must be present.
Order: Gets or sets the order of serialization and deserialization of a member. This can be important if clients rely on the order of the fields.
EmitDefaultValue: Gets or sets a value that specifies whether to generate a default value of null or 0 for a field or property being serialized.
When using the tcp binding the client and the host must be .net applications tcp higher performance
netNamedPipe – the fastest across machine
WCF provides a default set of bindings that should cover most of your requirements. If the default bindings don’t cover your requirements, you can build your own binding by extending from CustomBinding.
Text.MTOM (Message Transmission Optimization Mechanism) is a W3C standard to balance between efficiency and interoperability. The MTOM encoding transmits most XML in textual form, but optimizes large blocks of binary data by transmitting them as-is, without conversion to text.
Encoding could be Text, Binary and Text.MTOM
WCF supports base addresses, which enables you to host multiple endpoints under the same base address and which shortcuts the duplication of the scheme, host, port, and root path in your configuration.
33
34
If an exception occurs, this code creates a new System.ServiceModel.FaultException object with the details of the exception and throws it
The FaultCode object identifies the fault, note If you don’t create a FaultCode object, the WCF runtime will automatically generate a FaultCode object itself, with the name “Sender” and add it to the SOAP fault sent back to the client.
Throwing a faultexception is very simple and is not useful as it appears , it is not easy to predict what exceptions could occur when invoking WCF service a better solution is to use strongly typed soap faults .
A service contract can include information about any faults that might occur when executing an operation. If an operation in a WCF service detects an exception, it can generate a specific SOAP fault message that it can send back to the client application. The SOAP fault message should contain sufficient detail to enable the user, or an administrator, to understand the reason for the exception and if possible take any necessary corrective action. A client application can use the fault information in the service contract to anticipate faults and provide specific handlers that can catch and process each different fault. These are strongly typed faults
Service side
Create Custom Fault class as a Data contrcat
Use the FaultContract(typeof(your custom class))] attribute before the operation that may cause that exception
Throw the new type by the line throw new FaultException<your custom error>(custom error object)
Client side
Catch(FaultException<your custom class>obj)
{
obj.Detail.(all your class’s fields should appear here)
}
Summary
You should use the generic with the non generic exception handling
If you use strongly typed exceptions, you must specify every exception that an operation can throw in the service contract. If a service throws
a strongly typed exception that is not specified in the service contract, the details of the exception are not propagated to the client
This lack of detail is actually a security feature.
In these cases, you should catch the exception in the service, and if you need to send it to the client, raise an ordinary (non-generic) FaultException
Note:
You can turn the behavior on and off in the configuration file without rebuilding the application
If you enable this behavior in code, you cannot disable it by using the application configuration file