static void

WCF

.Net 1 remoting and webservices

See also WCF Ajax/JSON

Contracts

Service Contracts

//best practice to add name and namespace
[ServiceContract(Name = "Calculator", Namespace = "http://x.com/")]
public interface IService
{
    [OperationContract]
    Response Add(int number, [MessageParameter(Name = "Number2")]int number2);
}

Data Contracts

The messages that are passing to and from the OperationContract are data contracts.

//DataContract must be on classes/enums (and is not inherited).
[DataContract(Namespace = "http://y.com/")]
public class Response
{
    //Defaults: IsRequired=false (optional), EmitDefaultValue=true (passes nil for null/0)
    //IsRequired=true is not compatible with EmitDefaultValue=false
    [DataMember(IsRequired = false)]
    public int Total { get; set; }
}

There's also an [EnumMember] and a [CollectionDataContract]

Message Contracts

For detailed control of serialization (wrapping/ headers) use [MessageContract] over dataContract. See MSDN

//default wrapping: <s:Body><SpecificRequest><Description>...
//no wrapping (IsWrapped=false): <s:Body><Description>...
//renamed (WrapperName=): <s:Body><specificRequest>...
[MessageContract(WrapperName = "specificRequest")]
public class SpecificRequest
{
    //appears in the header, encrypted and signed
    [MessageHeader(ProtectionLevel =
        System.Net.Security.ProtectionLevel.EncryptAndSign)]
    public string User { get; set; }
 
    //add a specific namespace instead of the service contract
    [MessageBodyMember(Namespace = "http://mw.com/")]
    public string Description { get; set; }
}

More control

Message Exchange Patterns

Behavior

Extensibility

endpoint.Behaviors.Add(myIEndpointBehavior)

Address

ServiceHost and endpoints

In svc:

<%@ ServiceHost Service="Service1" %>

In code:

//or WebServiceHost for web
var host = new ServiceHost(
    //or pass new MyService() for singleton
    typeof(MyService),
    //params or array of base addresses
    new Uri("http://localhost:8000/"));
host.AddServiceEndpoint(
    typeof(IMyService),
    new WebHttpBinding(),
    //baseAddress + service name = full url.
    //If no base address, can use full address here.
    "MyService");

Hosts

Endpoints

Metadata

WCF Clients

Faults/Exceptions

See ,

Normal exceptions

IncludeExceptionDetailInFaults="True". Actually it returns a FaultException(typeof(ExceptionDetail)) but does not use a wsdl FaultContract

<behaviors>
  <serviceBehaviors>
    <behavior name="ServiceBehavior">
      <serviceDebug includeExceptionDetailInFaults="true" />

ServiceContract code:

#if DEBUG
    [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
#endif

Logging and handling exceptions: