wcf complete material

34
Deccansoft Software Services – WCF Chapter1: Introduction Evolution of WCF Evolution of Service Oriented Architecture (SOA) Four Tenets of SOA What is WCF Where does WCF Services fit in? Evolution of WCF: 1. Monolithic Applications a. Fox Pro and MS Access Applications which have both database and code at one place b. SQL Server / Oracle database were used on network but the application was still a monolithic one. c. Problem: Takes lots of time and No Code Reusability 2. Object Orientation – 1980’s a. Polymorphism b. Encapsulation c. Sub-classing d. Problem: It by itself didn’t facilitate the dynamic evolution of software at runtime. Once an application was built, it was static. There wasn’t an easy way to infuse new code into an application. 3. COM Components a. Write code once and reuse in multiple applications. b. Location Transparent c. Tight Coupling d. Runtime Metadata (self describing systems) e. Problem: Worked well on single machine(using method invocation on an object reference), we hit scaling problems when we tried to stretch it out and apply it as the substrate for distributed software integration (across machines) 4. DCOM a. Network Version of COM – Sharing COM objects over network b. Biggest failure of Microsoft as not at all reliable and scalable. 5. COM+ a. DCOM + MTS (Transaction Services) b. Object Pooling and Just In Time Activation. 6. .NET Remoting a. Option for .Net developers for Distributed application development. b. Best option only when both client and server are on same network. 7. Web Services a. Provides Objects functionality over HTTP b. Data is exchanged over the network in XML format. c. SOAP is the protocol used for communication. 8. WCF is the next generation of Web Service with following enhancements a. Supports sending messages not only using HTTP but also using TCP and Named-Pipe and MSMQ b. Support for sending messages using formats other than SOAP which includes Representational State Transfer (REST) and Plain Old XML (POX) c. Service can be hosting in different types of application unlike web services which needs Web server only. d. Built in support for Transaction and reliable sessions 1

Upload: abhi

Post on 22-Apr-2015

755 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: WCF Complete Material

Deccansoft Software Services – WCF

Chapter1: Introduction Evolution of WCF Evolution of Service Oriented Architecture (SOA) Four Tenets of SOA What is WCF Where does WCF Services fit in?

Evolution of WCF:1. Monolithic Applications

a. Fox Pro and MS Access Applications which have both database and code at one placeb. SQL Server / Oracle database were used on network but the application was still a monolithic one.c. Problem: Takes lots of time and No Code Reusability

2. Object Orientation – 1980’sa. Polymorphismb. Encapsulationc. Sub-classingd. Problem: It by itself didn’t facilitate the dynamic evolution of software at runtime. Once an application

was built, it was static. There wasn’t an easy way to infuse new code into an application.3. COM Components

a. Write code once and reuse in multiple applications.b. Location Transparentc. Tight Couplingd. Runtime Metadata (self describing systems)e. Problem: Worked well on single machine(using method invocation on an object reference), we hit

scaling problems when we tried to stretch it out and apply it as the substrate for distributed software integration (across machines)

4. DCOM a. Network Version of COM – Sharing COM objects over networkb. Biggest failure of Microsoft as not at all reliable and scalable.

5. COM+ a. DCOM + MTS (Transaction Services)b. Object Pooling and Just In Time Activation.

6. .NET Remotinga. Option for .Net developers for Distributed application development.b. Best option only when both client and server are on same network.

7. Web Servicesa. Provides Objects functionality over HTTP b. Data is exchanged over the network in XML format.c. SOAP is the protocol used for communication.

8. WCF is the next generation of Web Service with following enhancementsa. Supports sending messages not only using HTTP but also using TCP and Named-Pipe and MSMQ b. Support for sending messages using formats other than SOAP which includes Representational State

Transfer (REST) and Plain Old XML (POX)c. Service can be hosting in different types of application unlike web services which needs Web server

only.d. Built in support for Transaction and reliable sessions

Service Oriented Architecture: A service is a program that perform a task and that you can interact with through well defined messages.

o XML is the format in which Web Service and its client communicate with each other. Service Oriented applications consists of loosely coupled services that communicates through Messages and

Contractso Client does not instantiate the serviceo Messages are Requests and Responses exchanged between client and server.o Contracts specify what requests you can make on the service and how it will respond.

Four Tenets of Service Orientation1. Boundaries are Explicit

1

Page 2: WCF Complete Material

Deccansoft Software Services – WCF

Attributes based programming enables developers to explicitly define external service contracts. All communication occurs through messages. A Service is not aware of how the other service / client are constructed and it only knows how to send a message and how to receive a returned message.

2. Services are autonomousServices and consumers are independently versioned, deployed, operated and secured.These are going to evolve and can change any time without effecting the clients.

3. Share schema & contracts, not class: Contracts describe the messages services can send and receive.Data never includes behavior, object with data and behavior are local phenomenon

4. Compatibility based on policyService can define the circumstances under which client can communicate with them. For Example a Service may require authentication using X509 certificate or may require the client to be on the same network.Service policy statements are created automatically based on configuration, class attributes and method signatures. Client channels are automatically configured via retrieved service policy.

What is Windows Communication Foundation? Introduced in .NET Framework 3.0 and enhanced in .NET framework 3.5. It has classes in the Namespace

System.ServiceModel It unifies ASMX (Web Services), WSE (Web Service Extensions), .NET Remoting, Enterprise Services (Attribute

Based Prog.) and MSMQ (Asynchronous Communication). i.e. it is one model whether communication is internal or external.

It is a programming model for building service-oriented applications. It’s the MS Next Generation Platform for SOA.

It is the latest mechanism that developers can use to build distributed and interoperable applications that talk to each other.

Where does WCF Services fit in?Three Tier Arch

Presentation / Client Tier Business Tier Data Access Tier DatabaseService Tier

Presentation / Client Tier Service Tier Business Tier Data Tier Database

Basic Requirement for Developing WCF Service and ClientServer

Define and implement Service contractConstruct a Service Host Instance for the Service type exposing endpointsOpen the Communication channel

ClientRequires a copy of the Service contract and information about endpointsConstruct a communication channel for a particular endpoint and call operations

Next: Develop First WCF Service and Understand the code auto generated by VS.NET

2

Page 3: WCF Complete Material

Deccansoft Software Services – WCF

Chapter 2: Developing WCF Service Application and Client

Hosting WCF Service in IIS/ASP.NET Development Server Using a Service in the client application Understand Contracts in the service.

ServiceContract. OperationContract. DataContract.

Understand Instancing behavior in the service. Single PerCall PerSession

Building WCF Library based Host and Client application.

Walkthrough 1: IIS / ASP.NET as Hosting EnvironmentIn Server

1. File New Website WCF Service, Location = File System, Path=d:\WCF\HostInIIS\2. Delete existing Service.svc, IService.cs, Serivce.cs3. Add New Item WCF Service MathService4. Add to the Project “Complex” class as below

[DataContract]public class Complex{ private int _Real, _Imag;

[DataMember]public int Real{

get { return _Real; }set { _Real = value; }

}

[DataMember]public int Imag{

get { return _Imag; }set { _Imag = value; }

}}

5. Modify the IMathService and MathService as below[ServiceContract]public interface IMathService{

[OperationContract]int Add(int a,int b);

[OperationContract]Complex AddComplex(Complex c1,Complex c2);

[OperationContract] int GetCounter();}

public class MathService : IMathService{ public int Add(int a, int b) { Count++;

3

Page 4: WCF Complete Material

Deccansoft Software Services – WCF

return a+b;; }

public Complex AddComplex(Complex c1, Complex c2) { Count++; Complex c = new Complex(); c.Real = c1.Real + c2.Real; c.Imag = c1.Imag + c2.Imag; return c; } int Count; public int GetCounter() { return Count; }}

6. Run the MathService (Ctrl+F5). It Opens in the browser. Copy the URL.

In Client:1. Start New Instance of VS.NET2. Add Service Reference Use the URL from above (Step 6)3. Add Button and handle its Click event with the following code.

localhost.MathServiceClient ds = new localhost. MathServiceClient();

MessageBox.Show(ds.Add(100,200).ToString());

Demo of InstanceContextMode – Instancing behavior

In Server1. In IEmpService interface add a method called as GetCount()2. In EmpService declare a variable “Count” and in every method increment its value.3. In EmpService Implement GetCount to return “Count”4. For the EmpService add the attribute “ServiceBehaviour” with following

a. InstanceContextMode = PerSession – For every client a new Service instance is created and same is used for all the methods called by that client.

b. InstanceContextMode = PerCall – New Instance of Service is created for every method called by client c. InstanceContextMode = Single – Only one Service instance is created and the same is used by all the

clients for their methods called.5. For every “InstanceContextMode”, Update Service Reference in the client application and view return value of

“GetCount()” method

Walkthrough 2: Console Application as Hosting EnvironmentServer Application1. Create a WCF Library Project (WCFLibrary) File New Project Visual C# WCF WCF Service Library.

Project Name = WCFLibrary and SolutionName = WCFDemo2. Delete from that the default Service1 and also delete the App.Config file of the project.3. Add to the project a new WCF Service (MathService) which generates the following interface IDemoService and the

DemoService. using System;using System.Runtime.Serialization; using System.ServiceModel;namespace WCFLibrary{ [ServiceContract()] public interface IMathService { [OperationContract]

4

Page 5: WCF Complete Material

Deccansoft Software Services – WCF

int Add(int a, int b); [OperationContract] int Sub(int a, int b); } public class MathService : IMathService { public int Add(int a, int b) { return a + b; } public int Sub(int a, int b) { return a - b; } }

4. Add to the Solution a new Console Application (WCFServer)5. Add reference to System.ServiceModel (Net Tab) and WCFLibrary (Projects Tab)6. Move (Drag and Drop) the App.Config from ClassLibrary to Console Application Project and delete from WCFLibrary

Project.7. Edit the Autogenerated Main method in Program.csusing System.ServiceModelclass Program{

static void Main(){ ServiceHost sh; sh = new ServiceHost(typeof(WCFLibrary.MathService)); sh.Open(); Console.WriteLine("Server Started"); Console.WriteLine("Press any key to close the Server"); System.Threading.Thread.CurrentThread.Join();}

}Client Application:1. Create a Windows Application (MathServiceClient)2. Right Click on project select Add Service Reference 3. Handle Add Click and Sub Click as follows:

MathServiceClient ms = new MathService()private void btnAdd_Click(object sender, EventArgs e) { int res = dc.Add(int.Parse(txtN1.Text), int.Parse(txtN2.Text)); txtResult.Text = res.ToString(); }private void btnSub_Click(object sender, EventArgs e) { int res = dc.Sub(int.Parse(txtN1.Text), int.Parse(txtN2.Text)); txtResult.Text = res.ToString(); }

5

Page 6: WCF Complete Material

Deccansoft Software Services – WCF

Chapter3 – Endpoints in configuration file

End points in Configuration File. ABC - Address, Binding & Contract of the service in Configuration File. Understanding importance of base address. Importance of IMetadataExchange Contract / Endpoint. Configuring service behavior in configuration file WCF Service Configuration Editor Creating Endpoints through Code

Configuration File 1. Everything will be under <system.serviceModel>2. <services> contains service type definitions3. <endpoints> contains ABC for a service4. <binding> contains one or more binding sections to configure individual bindings5. <behavior> provides configuration for service.

Service Endpoints:1. A Service endpoint is used by Service Host to receive the request from the client and forward it to the service.2. A service can have one or more endpoints. 3. Every endpoint will have unique combination of ABC4. Can be defined in Code or in Configuration File

a. If configuration file is used it gives facility to change the endpoints when needed. We can either manually write the configuration file or use Service Configuration Editor.

b. If defined in code: No one can change the endpoints once the code is build and deployed.

Endpoint in config file:<endpoint address=""

binding="wsHttpBinding" contract="WCFLibrary.IMathService">

What is ABC?Address – Where do you send the message?Binding – How do you send the message?Contract – What should the message look like?

Metadata Exchange Endpoint: <endpoint address="mex" binding="mexHttpBinding"

contract="IMetadataExchange" />this is used by clients to add service reference i.e to generate the proxy class.Base Address:

<baseAddresses> <add baseAddress="http://localhost:8731/WCFLibrary/MathService" />

<add baseAddress="net.pipe://localhost/WCFService"/> <add baseAddress="net.tcp://localhost:8000/WCFService"/>

</baseAddresses>

Creating Endpoint Programmatically:Following can be written in Main:

ServiceHost sh = new ServiceHost(typeof(MathService)); System.ServiceModel.Description.ServiceEndpoint sep; sep = sh.AddServiceEndpoint(typeof(IService1), new WSHttpBinding(), "http://localhost:8731/WCFLibrary/MathService/");

sh.Open();...sh.Close();

Chapter 4: Channel Stacks & Bindings in WCF

6

Page 7: WCF Complete Material

Deccansoft Software Services – WCF

Understanding Channel Stack Introduction to Binding Types of Bindings. Binding Comparison Thumb rules in choosing endpoint binding Configuring a Service and Client for Multiple Bindings Binding Class Properties.

Understanding Channel Stack

1. Clients and services communicate by passing messages and the mechanism they use to communicate is a channel stack.

2. Channel Stack is made up of multiple channels as shown above.3. Protocol channels are responsible for preparing the message to be sent. These are optional. The order is important4. Transport channels are responsible for sending/receiving the message as per the protocol i.e. Http, TCP etc.5. Message Encoder converts the Message from XML to bytes for transport and Transport actually sends the message

over the socket.

Introduction to Binding:The Binding is an attribute of an endpoint and it lets you configure the channels like transport protocol, encoding and security requirements as shown below

One of the design goals of WCF is to unify the way distributed systems are developed prior to release of .Net Framework 3.0.

WCF offers a single development framework for all scenarios where distributed solutions were implemented using different technologies such as ASMX web services, .Net Remoting, COM+, etc.

WCF achieves this by configuring binding attributes of an endpoint. WCF lets you choose HTTP or TCP transport protocol, encoding, etc. just by tweaking the value of binding attribute for an endpoint.

Types of Bindings (All are class names which are inherited from “Binding” class). BasicHttpBinding WSHttpBinding WSDualHttpBinding WSFederatinHttpBinding NetNamedPipeBinding

7

Page 8: WCF Complete Material

Deccansoft Software Services – WCF

NetTcpBinding NetPeerTcpBinding NetMsmqBinding MsmqIntegrationBinding

Web Service Bindings1. BasicHttpBinding for SOAP 1.1 Compatibility (for ASMX based client – WS-Basic Profile 1.1)2. WSHttpBinding for SOAP 1.2 with WS* specification to support enterprise requirement of security, reliability,

ordered delivery and transaction management. This is also Interoperable.3. WSDualHttpBinding for callbacks over HTTP with WS* support (Not Interoperable)4. WSFederationHttpBinding for federation security and single sign on scenarios

Cross Process / Machine Bindings1. NetNamePipeBinding for in-process on same machine calls2. NetTcpBinding is used for same machine or cross-machine calls. It is not interoperable but is highly optimized

for .NET 3.0 and above clients. Its best replacement for .NET Remoting and COM+ model.3. NetPeerTcpBinding for same machine or cross machine peer to peer messaging.

Messaging Bindings1. NetMsmqBinding for reliable, transacted and persistent messaging over MSMQ2. MsmqIntegrationBinding for MSMQ interoperability with earlier MSMQ clients

Binding ComparisonBinding Class Name Transport Message

EncodingMessage Version

Security Mode

Tx Flow*

BasicHttpBinding HTTP Text/XML MTOM

SOAP 1.1 None X

WSHttpBinding HTTP Text/XML MTOM

SOAP 1.2WS-A 1.0

Message WS-AT

WSDualHttpBinding HTTP Text/XML MTOM

SOAP 1.2 WS-A 1.0

Message WS-AT

WSFederationHttpBinding HTTP Text/XML MTOM

SOAP 1.2WS-A 1.0

Message WS-AT

NetTcpBinding TCP Binary SOAP 1.2 Transport OleTx

NetPeerTcpBinding P2P Binary SOAP 1.2 Transport X

NetNamedPipeBinding Named Pipes

Binary SOAP 1.2 Transport OleTx

NetMsmqBinding MSMQ Binary SOAP 1.2 Message X

MsmqIntegrationBinding MSMQ X** X Transport XX = Not SupportedMTOM = Message Transmission Optimization MechanismWS-A = WS-AddressingWS-AT = WS-AtomicTransactionOleTx = OleTransactions* Transaction flow is always disabled by default, but when you enable it, these are the default tx protocols** This binding doesn’t use a WCF message encoding – instead it lets you choose a pre-WCF serialization format

Thumb rules in choosing endpoint' binding If you require your service to be consumed by clients compatible with SOAP 1.1, use basicHttpBinding for

interoperability If you require your service to be consumed within the corporate network, use netTCPBinding for performance If you require your service to be consumed over the internet and the client is a WCF compatible, use

wsHttpBinding to reap full benefits of WS* specifications If you require your service to be accessible only in the same machine, use netNamedPipeBinding If you require your service to be queue messages, use netMsmqBinding

8

Page 9: WCF Complete Material

Deccansoft Software Services – WCF

If you require your service to act as server as well as client in a peer to peer environment, utilize netPeerTcpBinding setting

Binding class Propertiesstatic void PrintBindingProperties(Binding binding) { Console.WriteLine("Name: " + binding.Name); Console.WriteLine("MessageVersion: " + binding.MessageVersion.ToString()); Console.WriteLine("Namespace: " + binding.Namespace); Console.WriteLine("OpenTimeout: " + binding.OpenTimeout.ToString()); Console.WriteLine("CloseTimeout: " + binding.CloseTimeout.ToString()); Console.WriteLine("SendTimeout: " + binding.SendTimeout.ToString()); Console.WriteLine("ReceiveTimeout: " + binding.ReceiveTimeout.ToString()); Console.WriteLine("Scheme: " + binding.Scheme); Console.WriteLine();}

static void Main(string[] args){ ServiceHost sh = new ServiceHost(typeof(Service1)); //Create WSHttpBinding System.ServiceModel.Channels.Binding binding = new WSHttpBinding(); //To Create and Endpoint System.ServiceModel.Description.ServiceEndpoint sep; sep = sh.AddServiceEndpoint(typeof(IService1), binding, ""); PrintBindingProperties(binding); //To Get Reference to binding mentioned on .config file. binding = sh.Description.Endpoints[0].Binding; PrintBindingProperties(binding); sh.Open(); Console.WriteLine("Service has started"); Console.WriteLine("Press any key to stop the server"); System.Console.ReadKey(true); Console.WriteLine("Service has stopped"); sh.Close();}

Chapter 5: Understanding Service and Data Contracts About Service Contract

9

Page 10: WCF Complete Material

Deccansoft Software Services – WCF

Data Contract & Data Member Versioning using Interface IExtensibleDataObject Version Tolerance

Implications of Modifying Service Operations Implications of Modifying Data Contracts

Working with Known Types

In every service oriented architecture, services share schemas and contracts, not classes and types. What this means is that you don't share class definitions neither any implementation details about your service to consumers.Everything your consumer has to know is your service interface, and how to talk to it. In order to know this, both parts (service and consumer) have to share something that is called a Contract.

ServiceContract The ServiceContract attribute maps a CLR interface to a technology-neutral service contract Service Contract describes what the service can do. It defines some properties about the service, and a set of actions

called Operation Contracts. Operation Contracts are equivalent to web methods in ASMX technologyProperties of ServiceContract:

o The ConfigurationName property specifies the name of the service element in the configuration file to use. o The Name and Namespace properties control the name and namespace of the contract in the WSDL

<portType> element.o The SessionMode property specifies whether the contract requires a binding that supports sessions.o The CallbackContract property specifies the return contract in a two-way (duplex) conversation.o The HasProtectionLevel and ProtectionLevel properties indicate whether all messages supporting the

contract have a explicit ProtectionLevel value, and if so, what that level is.o

Data Contract Describes how CLR types are mapped to XSD schema definitions Enables complex types to be serialized and deserializes so that is can be exchanged between client and server.

DataContractSerializer is used for serializing data contracts As long as the data passed between the services conforms to the same contract, all the services can process the data.

This processing is also known as a loosely coupled system. A data contract can also accommodate later versions of itself. That is, when a later version of the contract includes

extra data, that data is stored and returned to a sender untouched. To do this we should implement the IExtensibleDataObject interface.

Properties of Data Contract:Name: Gets or sets the name of the data contract for the type.Namespace: Gets or sets the namespace for the data contract for the type.

DataMemberAttribute: It is applied in conjunction to DataContractAttribute to identify members of the type that are part of DataContract. You can apply the DataMemberAttribute to private fields or properties. Be aware that the data returned by the

member (even if it private) will be serialized and deserialized, and thus can be viewed or intercepted by a malicious user or process.

Properties to which the DataMemberAttribute attribute has been applied must have both get and set fields; they cannot be get-only or set-only.

Properties of DataMemberAttribute:IsRequired: Gets or sets a value that instructs the serialization engine that the member must be present when reading or deserializing.Name: Gets or sets a data member name.Order: Gets or sets the order of serialization and deserialization of a member.

10

Page 11: WCF Complete Material

Deccansoft Software Services – WCF

Version Tolerance1. WCF contracts are version tolerant by default2. Forgive missing, non required data3. Ignore superfluous / extra data4. This is handled by DataContractSerializer.

ServiceContract changes Impact to existing clientsAdding new parameters Client Unaffected

New parameters initialized to default value in the service.Remove Parameters Client Unaffected

Parameters passed by client are ignored, data lost at the serviceModifying Parameters types An exception will occur if the incoming type from the client cannot be converted

to the parameter data type.Modifying return value types An Exception will occur if the return value form the service cannot be converted

to the expected data type in the client version of the operation signatureAdding new operations Client unaffected

Will not invoke operations it knows nothing aboutRemoving operations An exception will occur

Messages sent by the client to the service are considered to be using an unknown action header.

DataContract changes Impact on existing clientsAdd new non-required member Client unaffected

Missing values are initialized to defaultsAdd new required member An exception is thrown for missing valuesRemove non-required members Data lost the services

Unable to return the full data set back to the clientNo Exceptions

Remove required members An exception is thrown when client receives response from the service with missing values

Modify existing member data types

If types are compatible, no exception but may receive unexpected result

Known TypesNormally, when passing parameters and return values between a client and a service, both endpoints share all of the data contracts of the data to be transmitted. However, this is not the case in the following circumstances: The sent data contract is derived from the expected data contract. In that case, the transmitted data does not have

the same data contract as expected by the receiving endpoint. The declared type for the information to be transmitted is an interface. The declared type for the information to be transmitted is Object. Some types, which include .NET Framework types, have members that are in one of the preceding three categories.

For example, Hashtable uses Object to store the actual objects in the hash table. When serializing these types, the receiving side cannot determine in advance the data contract for these members

Known Types can be declared at 3 placesStep1: Add the following classes to the Library Project. [DataContract] public class TrainingEmployee : Employee { [DataMember] public string Subject { get; set; } } [DataContract] public class DevelopmentEmployee : Employee {

11

Page 12: WCF Complete Material

Deccansoft Software Services – WCF

[DataMember] public string LanguageofPrograming { get; set; } }

Step 2: Use any one of the following options:Option 1: [ServiceContract] [ServiceKnownType(typeof(TrainingEmployee))] [ServiceKnownType(typeof(DevelopmentEmployee))]

public interface IEmpService {

. . . }

Option 2: [DataContract] [KnownType(typeof(TrainingEmployee))] [KnownType(typeof(DevelopmentEmployee))] public class Employee { . . . }Option 3: Configuring known types through Config File.

<system.runtime.serialization> <dataContractSerializer> <declaredTypes> <add type="WcfServiceLibrary1.Employee, WcfServiceLibrary1"> <knownType type="WcfServiceLibrary1.TrainingEmployee, WcfServiceLibrary1"/> <knownType type="WcfServiceLibrary1.DevelopmentEmployee, WcfServiceLibrary1"/> </add> </declaredTypes> </dataContractSerializer></system.runtime.serialization>

12

Page 13: WCF Complete Material

Deccansoft Software Services – WCF

Chapter 6: Handling WCF Exceptions/Faults

Overview Producing Faults

SOAP fault with FaultCode and FaultReason Culture specific SOAP fault Strongly Typed SOAP fault

Consuming Faults Proxy State for Managed Exceptions Vs SOAP Fault

Overview WCF does not communicate CLR Exceptions. WCF Exceptions are passed as SOAP Messages. The underlying principle of service-oriented error handling consists of

SOAP fault messages, which convey the failure semantics and additional information associated with the failure (such as the reason).

For security purpose, an exception message doesn’t contain any information about the actual exception. During development we can configure the service to return more detailed exception information.

<serviceBehaviors> <behavior name="ServiceBehavior"> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior></serviceBehaviors>or[ServiceBehavior(IncludeExceptionDetailInFaults=true)]public class DemoService : IDemoService{ . . . }

Managed Exceptions Vs SOAP Fault

If a managed exception is thrown from a service operation, client is immediately reported with a “FaultException” and the communication channel of the client is faulted and the proxy object cannot be used for calling any more methods. If it is used then “CommunicationObjectFaultedException” is thrown in the client application.

If a managed exception is thrown from a one way service operation, client is not immediately reported about the exception in the service. If the client application after this calls any other method then “MessageSecurityException” will be reported to client and the communication channel will be in faulted state.

If a “FaultException” is thrown from the service operation on server then the client application can handle this FaultException and the communication channel of client and server will not be in faulted state.

Producing Faults Use FaultException Class to customize the Error Message the service returns.

o Clients can’t distinguish types of faultso Use FaultCode to specify a SOAP fault codeo Use FaultReason to specify the description of the fault. It supports locale based translation of message

SOAP fault with FaultCode and FaultReasonthrow new FaultException("Reason for Exception", new FaultCode("SomeError"))

Culture specific SOAP fault List<FaultReasonText> lstReasons = new List<FaultReasonText>(); lstReasons.Add(new FaultReasonText("This is in english",new System.Globalization.CultureInfo("en-US"))); lstReasons.Add(new FaultReasonText("This is in french",new System.Globalization.CultureInfo("fr-FR"))); lstReasons.Add(new FaultReasonText("This is in hindi",new System.Globalization.CultureInfo("hi-IN"))); FaultReason reason = new FaultReason(lstReasons); throw new FaultException(reason, new FaultCode("SomeError"));

Strongly typed SOAP fault Most services which require error handling also require additional information to be passed with the error

notification. This information can be transferred to the client as a standard WCF data contract, in the disguise of a fault.

13

Page 14: WCF Complete Material

Deccansoft Software Services – WCF

The contractual specification that a particular service operation can result in the specified fault is called a fault contract. The following code demonstrates a service operation contract that can result in the MyApplicationFault fault message:

public class DemoException{ public string Message; public int Value;}[ServiceContract]public interface IExceptionDemoService{ [OperationContract()] [FaultContract(typeof(DemoException))] void ThrowStronglyTypedFault();}

Use the following code to report error:DemoException ex = new DemoException(){Message="Demo",Value=1};throw new FaultException<DemoException>(ex);

Consuming FaultsIMyService proxy = new MyServiceClient(); try { proxy.MyMethod();}catch (FaultContract<DemoException> myFault) { MyApplicationFault detail = myFault.Detail; //Do something with the actual fault}catch (FaultException otherFault) { ... }

14

Page 15: WCF Complete Material

Deccansoft Software Services – WCF

Chapter 7: Message Exchange Patterns

Request – Reply Pattern One way Operations Duplex Pattern Duplex Publisher Subscriber Example

There are three types of Message Exchange Patters1. Request – Reply:

a. Client sends a message to the service and waits for the service to send the message back2. One way:

a. Client sends a message to the service and doesn’t wait for the replyb. Used for logging or storing datac. Set IsOneWay property of methods OperationContract to true

3. Duplex Patterna. Client and Service can initiate communication by sending a message to each other.b. Use when service needs to notify the client that it finished processing an operation or when service can

publish events to which client can subscribe.

Example of One way: Client application should Log to file the start time and stop time with the ServiceProxy.LogStartTime (WindowsIdentity.GetCurrent ().Name);

Example of Duplex CommunicationGeneral Steps to Setup Duplex Communication

1. Add a one-way operation to the service contract2. Add a call back contract to the service3. Associate the call back contact with the service contract.4. Use binding that supports duplex binding (WsHttpBinding should be replaced with WSDualHttpBinding). 5. Create a class in the client that implements the callback contract.6. Create a proxy class and pass it the context information for the service.

Step 1: Add a Service Contract to the class library project. [ServiceContract ()] public interface IDemoService { [OperationContract(IsOneWay = true)] void SendEmailAndNotifyCompletion(string name,string toEmailId,string body); }Step 2: Add a new interface ICallbackService public interface ICallbackService { [OperationContract(IsOneWay = true)] void OperationCompleted(string message); }Step 3: Associate the callback contract with service contract [ServiceContract (CallbackContract = typeof(ICallbackService))]Step 4: Implement NotifyClient method public void SendEmailAndNotifyCompletion(string name, string toEmailId, string body) { Console.WriteLine("Now sending email"); //simulate sending of email by sleeping for 5 secs. System.Threading.Thread.Sleep(5000); //Callback client method. ICallbackService callback = OperationContext.Current.GetCallbackChannel<ICallbackService>(); callback.OperationCompleted(string.Format("Hello {0}, Your email to {1} is sent", name, toEmailId)); ; Console.WriteLine("Email Sent"); } Step 5: Change the binding on server to WSDualHttpBindingIn Client Application:

15

Page 16: WCF Complete Material

Deccansoft Software Services – WCF

Step 6: Add the service reference.Step 7: In Form implement IDemoServiceCallback public partial class DemoForm : Form, localhost.IDemoServiceCallback { DemoServiceClient proxy; private void DemoForm_Load(object sender, EventArgs e) { InstanceContext ic; ic = new InstanceContext(this); proxy = new DemoServiceClient(ic); } public void OperationCompleted(string message) { MessageBox.Show(message); } private void btnSendEmail_Click(object sender, EventArgs e) { string name = System.Security.Principal.WindowsIdentity.GetCurrent().Name; proxy.SendEmailAndNotifyCompletion(name,txtToEmailId.Text, txtEmailBody.Text); } }

16

Page 17: WCF Complete Material

Deccansoft Software Services – WCF

Chapter 8: Transactions

What is Transaction and ACID How to enable Transaction in WCF Service TransactionScope in to begin a transaction. Transaction Isolation Transactions and Sessions

Transaction: Logical units of work comprising of multiple activities that should all succeed or all failTransaction needs to meet ACID principles:

Atomic: Transaction executes at once and all of the work occurs or none does. Consistency: Needs to preserve data consistency i.e. commit or rollback Isolation: Needs to be independent of other transactions and one transaction should not be allowed to see the

uncommitted state of another transaction. Durable: transactions are recoverable i.e. needs to log its state so that it should know what do undo if the

transaction fails..NET framework provides System.Transactions Namespace and TransactionScope class.

To Enable Transaction in WCF Service1. Create New Binding. Please note the Bindings that supports transaction: NetTcpBinding, NetNamedPipeBinding,

WSHttpBinding, WSDualHttpBinding, WSFederationBinding<bindings>

<wsHttpBinding><binding transactionFlow="true" name="WSHttpTransactionBindingConfig"/>

</wsHttpBinding></bindings>

2. Assign the binding to the endpoint. <endpoint . . . bindingConfiguration="WSHttpTransactionBindingConfig">3. Add the following attribute to the participating methods in the Service Contract interface

[TransactionFlow(TransactionFlowOption.Mandatory)] NotAllowed: A transaction should not be flowed. This is the default value. Allowed: Transaction may be flowed Mandatory: Transaction must be flowed

4. For the method implemented by the Service class add the following [OperationBehavior(TransactionScopeRequired=true,TransactionAutoComplete=true)]Default value of TransactionScoreRequired is false.Default value of TransactionAutoComplete is true

TransactionScopeRequired

Binding permits

transaction flow

Caller flows

transaction

Result

False False No Method executes without a transaction.True False No Method creates and executes within a new

transaction.True or False False Yes A SOAP fault is returned for the transaction header.False True Yes Method executes without a transaction.True True Yes Method executes under the flowed transaction.

TransactionIsolationLevel:Optionally you may configure transaction isolation in ServiceBehaviorAttribute

[ServiceBehavior(TransactionIsolationLevel=System.Transactions.IsolationLevel.Serializable)] Different transaction isolation levels in WCF

Read Uncommitted: So, you can read an uncommitted transaction that might get rolled back later. This isolation level is also called dirty read. This is the lowest isolation level.

Read Committed: It ensures that physically corrupt data will not be read and will never read data that another application has changed and not yet committed, but it does not ensure that the data will not be changed before the end of the transaction.

Repeatable Read: It means that locks will be placed on all data that is used in a query, and other transactions cannot update the data.

17

Page 18: WCF Complete Material

Deccansoft Software Services – WCF

Serializable: It does not allow any modification and addition of new data till the transaction is completed. This is considered to be a very restrictive level.

Snapshot: It raises error on modifying a data that has already been changed by any transaction.

In some bindings transaction protocol can be set.<binding transactionProtocol="OleTransaction"/>

a. OleTransaction: Optimal for .NET clientb. Web Service Atomic Transaction: Use when clients are not .NET

Note: WCF runtime chooses protocol by default.

Starting a Transaction in client application:1. Add reference to System.Transactionsusing (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required)){ //Call WCF Service methods.

ts.Complete();} Required: A transaction is required by the scope. It uses an ambient transaction if one already exists. Otherwise, it

creates a new transaction before entering the scope. This is the default value. RequiresNew: A new transaction is always created for the scope. Suppress: The ambient transaction context is suppressed when creating the scope. All operations within the scope

are done without an ambient transaction context.

Transactions and Sessions:By default, when you add transactions, client uses a different service instance for each call so no state is maintained.To configure transactional service to maintain state1. [ServiceContract(SessionMode=SessionMode.Required)]2. [ServiceBehavior(InstanceContextMode=InstanceContextMode.PerSession,TransactionAutoCompleteOnSessionClose=

true)]3. [OperationBehavior(TransactionScopeRequired=true,TransactionAutoComplete=false)]

18

Page 19: WCF Complete Material

Deccansoft Software Services – WCF

Chapter 9: Microsoft Message Queue

Introduction Advantages of using MSMQ Transactional Queues Setup and View MSMQ Server Steps to follow to Build a MSMQ application

Introduction Microsoft Message Queuing, or MSMQ, is technology for asynchronous messaging. MSMQ can be used whenever there's need for two or more applications to send messages to each other without

having to immediately know results. MSMQ can communicate between remote machines, even over internet. It's free and comes with Windows, but is

not installed by default. The MSMQ server is similar to an e-mail server, but it's designed to let applications "talk" to each other, whereas a

mail server is designed to let humans talk to each other

Advantages of using MSMQ Increase application robustness, as clients can send messages even when services are not running. Increase application scalability, because multiple service instances can be used to process messages from a single

queue. Improve client responsiveness, which eliminates the need for clients to wait for a response from the service. Reduce dependencies between client and services, because all communication is indirect via queues. Ensure the durability of messages, because they can survive service and system failures

Transactional Queues When transactions are used to send and receive messages, there are actually two separate transactions. When the

client sends messages within the scope of a transaction, the transaction is local to the client and the client queue manager. When the service receives messages within the scope of the transaction, the transaction is local to the service and the receiving queue manager.

It is very important to remember that the client and the service are not participating in the same transaction; rather, they are using different transactions when performing their operations (such as send and receive) with the queue.

Steps to Install and Verify MSMQ Server1. Go to Control Panel Program and Features Turn Windows Features on or off2. Check Microsoft Message Queue (MSMQ) Server OK3. Go to Control Panel Administrative Tools Computer Management4. Expand Services and Application Message Queuing

19

Page 20: WCF Complete Material

Deccansoft Software Services – WCF

Steps to build MSMQ application1. ServiceContract interface should have One way Operations [OperationContract(IsOneWay=true)]2. InstanceContext of Service should be PerCall

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]3. Create an MSMQ binding

<bindings> <netMsmqBinding> <binding name="netMsmq" exactlyOnce="false"> <security mode="None" /> </binding> </netMsmqBinding></bindings>

Note: ExactlyOnce = True if Transactional Queues are used (This is default value). ExactlyOnce = False if Non-Transactional Queues are used. ExactlyOnce, when set to true, indicates that Message Queuing (MSMQ) ensures that a sent message is delivered to

the receiving message queue once and only once. If delivery fails, the message is sent to the dead-letter queue. If the queue is not transactional: In app.config of client application we have to set

<binding durable="false"...> By default with the NetMsmqBinding, transport security is enabled. By default, the authentication mode is set to

Windows. For MSMQ to provide the authentication it must be part of a domain and the Active Directory integration option for MSMQ must be installed. If you run the sample on a computer that does not satisfy these criteria, you receive an error. This is the reason Security mode is set to “None”.

4. Connect the above binding to the endpoint. <endpoint address="net.msmq://localhost/private/Test" binding="netMsmqBinding" contract="Messaging.IMessagingService" bindingConfiguration="netMsmqConfig" />

Note the address. Test is the Queue Name and private should be used for private queues.5. In Entry point method “Main” of server, write the following code to create a Queue if one doesn’t exists.

string queueName = ".\\private$\\Test";if (!MessageQueue.Exists(queueName)) MessageQueue.Create(queueName, true);

Note: Second parameter should be true to create a Transactional Queue.6. Set OperationBehaviorAttribute as given below

[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]7. In the client application, add the reference and write the following code

using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Required)){ //Instantiate proxy proxy.Close(); scope.Complete();}

20

Page 21: WCF Complete Material

Deccansoft Software Services – WCF

Chapter 10: WCF Security

1. Concepts.2. Security Mechanisms.3. Default Security Settings.4. Demonstrate how Messages are encrypted.5. Authentication

a. Windows Authenticationb. HTTPS / SSL Authentication.c. ASP.NET Membership Authenticationd. Custom Authentication

6. Authorizationa. Windows Group/Role based Authorizationb. Custom Role based Authorizationc. ASP.NET Role Providerd.

Security ConceptsAuthentication: Client and service have clear Identity. Client has to provide login Credentials Authorization: Client has permissions or not to call operations of the service. Confidentiality: Only client can read data passed between client and service. Data is encrypted on networkIntegrity: Messages have not been tampered with when they are on the network

Security Mechanisms1. Transport Level Security

Security applied at OS level at Network or transport level and before the message is sent Encryption based on binding

o HTTPS uses SSLo TCP uses Transport Layer security (TLS)o Can require clients to pass credentials for authentication

2. Message Level Security Messages are encrypted based on WS-Security standard and signed before they are sent. Can require to client pass credentials for authentication

Pros and Cons of Message Level and Transport Level Security1. Transport Level Security:

o Pros: Faster and can benefit from hardware acceleration. o Cons: Provides only point to point encryption. So if the client uses transport level security and send the

message to service, which then forwards the message to another service for processing. The intermediary service will decrypt the message and could potentially alter it.

2. Message level Security o Cons: Slowero Cons: Requires both client and service must support WS-Security specification. This will make

interoperability more difficulto Pros: Provides end to end encryption since message is encrypted. Intermediary service cannot read or

decrypt the message. o Pros: More options for credentials.

Note: In situation where the client sends the message directly to service that performs the operation, we can safely use either of the mechanism to secure the message.

Default Security Settings1. BasicHttpBinding

No Security because interoperable with ASMX2. WsHttpBinding

Message Level Security Messages are encrypted

3. NetTcpBinding Transport level security

21

Page 22: WCF Complete Material

Deccansoft Software Services – WCF

Messages are not encrypted, but packets are.

Demo how messages are encrypted.1. Go to Tools WCF Configuration Editor Open the config file in Server.2. Enable message logging (Diagnostics Click on Enable Message Logging)3. Select Messages Logging and Set LogMessagesAtServiceLevel = True, LogMessagesAtTransportLevel = True4. Using basicHttpBinding build and run Server and Client application. Log file will be created.

o Open the Log file using Service Trace Viewer: Start Programs Microsoft Windows SDK Service Trace Viewer. Then in Messages Tab – View Message.

o Note that client built and client sent messages will be same and not encrypted. (Body of SOAP envelope is easily readable)

5. Now Delete the Log file.6. Repeat 4 this time using WsHttpBinding

o Open the Log file using Service Trace Viewer – In Message Tab – View Messages.o Note that client and service built are not encrypted but what messages client and service sent are

encrypted.Note: For every message we will have two entries.

AuthenticationIdentify users and control who can access a serviceClient can authenticate itself by passing credentials to the service either using Windows Credentials, Digital certificates or User name and password.

<security mode="Transport"><transport clientCredentialType="Windows"/>

</securityTransport Security Credentials

Windows – Use Windows authentication to authenticate. Basic – Use user name and password against Active Directory (HTTP only) Certificate – Use an X. 509 certificate NTLM – Use a challenge-response scheme against Windows accounts (HTTP only) None – No authentication.

Message Security Credentials Windows – Use Windows authentication to authenticate Username – Use user name and password against either Windows accounts or ASP.NET membership provider Certificate – Use an X. 509 certificate IssueToken – Use Secure Token Service to issue tokens (eg. Windows CardSpace) None – No authentication

Default Security Settings BasicHttpBinding: No Security WsHttpBinding: Client credentials are Windows tokens. NetTcpBinding: Client credentials are Windows tokens.

Demo: Windows AuthenticationIn Server:Part 1:Print in Operation: System.Threading.Thread.CurrentPricipal.Identity.Name Print the following properties for basicHttpBinding, wsHttpBinding and netTcpBinding.

1. Securty.Mode, 2. Security.Message.AlgorithmSuite, 3. Security.Message.ClientCredentialType, 4. Security.Transport.ClientCredentialType------BasicHttpBinding Properties Output------Security.Mode: TransportSecurity.Message.AlgorithmSuite: Basic256Security.Message.ClientCredentialType: UserNameSecurity.Transport.ClientCredentialType: Windows------WSHttpBinding Properties Output ------Security.Mode: Message

22

Page 23: WCF Complete Material

Deccansoft Software Services – WCF

Security.Message.AlgorithmSuite: Basic256Security.Message.ClientCredentialType: WindowsSecurity.Transport.ClientCredentialType: Windows------NetTcpBinding Properties Output ------Security.Mode: TransportSecurity.Message.AlgorithmSuite: Basic256Security.Message.ClientCredentialType: WindowsSecurity.Transport.ClientCredentialType: Windows

Part2: To pass windows credentials from client in basicHttpBinding:1. Create Certificate

a. Go to Control Panel Administrative Tools Internet Information Service Manager b. Under IIS Section Open Server Certificate Create a Self Signed Certificate Mention

Certificate Name ( WCFSecurityDemo) OK2. Enable SSL

a. Default Website Binding (From right side)b. Add… Type=https, IPAddress=All Unassigned, SSL Certificate=WSSecurityDemo OK

3. Enable end point port of HTTPS for Securitya. Go to Certificate - Double click on certificateb. Copy Thumbprint i.e. Certificate Hash (certhash)c. Go to command prompt (Accessories Command Prompt Right Click Run as Administrator.d. Type the following command

i. netsh http add sslcert ipport=0.0.0.0:8733 certhash=7b91ad7e30a975cecf8b028c15839e30f88596f1 appid={5029A020-5D47-4eb2-ABC3-048EC57B7FD7}

(8733 is the port in config file / certhash without spaces) To generate appid (Tools Create GUID Select Registry Format Copy Exit

e. Add the following under <System.ServiceModel><bindings> <basicHttpBinding> <binding name="BasicHttpConfig"> <security mode="Transport"> <transport clientCredentialType="Windows"/> </security> </binding </basicHttpBinding></bindings>

4. Add the following end point to the service app.config<endpoint address="https://localhost:8733/basic"

binding="basicHttpBinding" contract="WCFLibrary.IService1" bindingConfiguration="BasicHttpConfig"/>

5. Run the server.6. Update the Service Reference on the client.7. Run the client. It will give error by default because WCF runtime does not trust self certificate by default so

we need a certificate from someone like verisign.8. Add the following class to client application

using System;using System.ServiceModel;using System.Net;using System.Net.Security;using System.Security.Cryptography.X509Certificates;class PermissiveCertificatePolicy{ string subjectName; static PermissiveCertificatePolicy currentPolicy; PermissiveCertificatePolicy(string subjectName) {

23

Page 24: WCF Complete Material

Deccansoft Software Services – WCF

this.subjectName = subjectName; ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(RemoteCertValidate); } public static void Enact(string subjectName) { currentPolicy = new PermissiveCertificatePolicy(subjectName); } bool RemoteCertValidate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors error) { return true; }}

9. Before the proxy instance is created call PermissiveCertificatePolicy.Enact(“CN=WCFSecurityDemo”)10. Note that for basicHttpBinding client is sending Windows Credentials.

Basic Authentication

Situation: User accesses service over the Intranet and logs on with domain username and password.Enable WCF support on IIS1. Go to command prompt (Accessories Command Prompt Right Click Run as Administrator2. Run: "C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe" -i

Install the basic authentication module support for IIS. 1. In Vista it is: Control Panel -> Programs -> Turn Windows features on or off2. In Server 2008: Server Manager -> Roles -> Web Server -> Add Role ServicesThen in the Tree view it is: Internet Information Services -> World Wide Web Services -> Security - > Basic Authentication1. Ensure that the SSL Certificate is already installed in IIS (Steps are shown in the previous example)2. Create a WCF Service using IIS Host. File New Website WCF Service Http WCFDemoService3. Add the following to web.config.

<bindings> <wsHttpBinding> <binding name="WSHttpBindingConfig"> <security mode="Transport"> <transport clientCredentialType="Basic"/> </security> </binding> </wsHttpBinding> </bindings>

4. In IIS enable Basic Authentication for the Application.5. In Client [pass credentials to service in code].

proxy.ClientsCredentials.UserName.UserName = “<Enter Windows Username>”proxy.Client.Credentials.UserName.Password = “<Enter Password>”

ASP.NET Membership Provider1. ASP.NET provides membership management2. Provides user authentication3. User information is stored by default in SQL server but you can use your own store4. You don’t have to write the code to authenticate users.Demo:1. Create a WCF Service using IIS Host. File New Website WCF Service Http

Https://Localhost/MembershipDemoService2. Go to Website ASP.NET Configuration Security Add Users3. In Web.config under <system.web> do the following

<authentication mode="Forms" /><authorization>

<deny users="?"/></authorization>

24

Page 25: WCF Complete Material

Deccansoft Software Services – WCF

4. Using WCF Configuration Editor Create New Binding <bindings> <wsHttpBinding> <binding name="WSHttpBinding"> <security mode="TransportWithMessageCredential"> <transport clientCredentialType="None" /> <message clientCredentialType="UserName" /> </security> </binding> </wsHttpBinding> </bindings>

5. Using WCF Configuration Editor Edit ServiceBehavior <serviceCredentials>

<userNameAuthentication userNamePasswordValidationMode="MembershipProvider"membershipProviderName="AspNetSqlMemberShipProvider" />

</serviceCredentials>

AuthorizationControl who can access a service and what operations of the service

Role based Authorization Options: Use Windows Groups Use custom roles ASP.NET Role Provider

1. Authorization Based on Windows Groups.1. Enable Windows Authentication on the binding.2. Add the following attribute to the method

[PrincipalPermission [SecurityAction.Demand, Role="BUILTIN\\BackupOperators")]3. To control from inside the method:

var user = new WindowsPrincipal ( (WindowsIdentity) System.Threading.Thread.CurrentPrincipal.Identity);if (! User.IsInRole (WindowsBuiltInRole.Administrator)

Throw new SecurityException ("Access denied");

2. Authorization based on Generic Identity (Custom Roles)1. In service class declare the following variable

public static GenericPrincipal UserPrincipal = null;2. In every method which is secured add the following in the beginning.

if (UserPrincipal.IsInRole("Manager") != true)throw new SecurityException("Access denied");

3. To the Library Project add the following classpublic class UserValidation : UserNamePasswordValidator{ public override void Validate(string userName, string password) { //For Demo lets validate as: If username and password are same then its a valid user others invalid. if (userName != password) throw new SecurityTokenException("Unknown Username or Incorrect Password"); //based on username attach role to the user. GenericIdentity identity = new GenericIdentity(userName); if (userName.ToUpper().StartsWith("m")) Service1.UserPrincipal = new GenericPrincipal(identity, new string[] { "Manager" }); else Service1.UserPrincipal = new GenericPrincipal(identity, new string[] { "User" }); }}

4. In App.Config of server application edit the ServiceBehavior

25

Page 26: WCF Complete Material

Deccansoft Software Services – WCF

<serviceBehaviors> <behavior name="DemoLibrary.Service1Behavior"> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="false" /> <serviceCredentials> <serviceCertificate findValue="<Your Machine Name>" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" /> <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="DemoLibrary.UserValidation, DemoLibrary" /> <windowsAuthentication allowAnonymousLogons="true" /> </serviceCredentials> </behavior></serviceBehaviors>

5. Add the following binding to App.Config<wsHttpBinding> <binding name="WSHttpBindingConfig"> <security mode="Message"> <transport clientCredentialType="None"/> <message clientCredentialType="UserName" /> </security> </binding></wsHttpBinding>

6. Change the endpoint <endpoint address="" binding="wsHttpBinding" contract="DemoLibrary.IService1"

bindingConfiguration="WSHttpBindingConfig"/>7. In the client application provide the username and password along with the request

proxy.ClientCredentials.UserName.UserName = "MA1";proxy.ClientCredentials.UserName.Password = "MA1";Console.WriteLine(sc.GetData(10));

26