Pages

WCF

Introduction of WCF

Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows.and it (Code named Indigo) is a programming platform  and  runtime system for building, configuring and deploying network-distributed services.WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. Windows Communication Foundation (WCF) is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.
different technology combined to form WCF. 


WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on operation systems that support it. Presently this list consists of Windows Vista (client and server), Windows XP SP2, and Windows Server 2003 SP1 or their later versions

Advantage

  • Its made of a lot of different components, so you can create new components for security, transport, authentication
  • In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  • Its faster than ASMX
  • Supports Scaling/Load Balancing
  • WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.
  • Its Interoperability, for java, and more.
  • WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net
  • WCF services provide better reliability and security in compared to ASMX web services.
Disadvantages
 
A drawback would be that, WCF is Microsoft's implementation of SOA and hence its APIs are solely controlled by MS which makes interoperability a bit difficult. Also, to deploy WCF apps, you will need more underlying hardware resources on the platform on which the WCF applications will be running, since there is an additional layer of abstraction to deal with.

Features of WCF

Workflow Services
Workflow Service explains  how to create and configure workflow services.

Endpoints: Addresses, Bindings, and Contracts
Explainhow to control multiple aspects of your service.

Data Transfer and Serialization
Explain how serialization of data can be tailored for interoperation or future compatibility.

Sessions, Instancing, and Concurrency
Explain the instancing and session modes of WCF and how to select the right mode for your application.

Transports in Windows Communication Foundation
Explain how to configure the transport layer, the lowest level of the channel stack.

Queues and Reliable Sessions
Explain queues, which store messages from a sending application on behalf of a receiving application and later forward these messages to the receiving application.

Transactions
Explains how to created transacted operations that can be rolled back if needed.

Windows Communication Foundation Security
Explain how WCF security helps you to create applications that have confidentiality and integrity. Authentication and authorization are also available, as are auditing features.

Peer-to-Peer Networking
Details how to create peer services and clients.

Metadata
Explainmetadata architecture and formats.

Clients
Explain how to create a variety of clients that access services.

Hosting

Explain hosting. A service can be hosted by another application, or it can be self-hosted.

Interoperability and Integration
Explain how to use WCF to extend your existing logic rather than having to rewrite it if you have a substantial investment in component-based application logic hosted in COM+.

WCF Web HTTP Programming Model
Explainthe WCF Web Programming Model that allows developers to expose WCF service operations to non-SOAP endpoints.

WCF Syndication
Explainsupport to easily expose syndication feeds from a WCF service.

AJAX Integration and JSON Support
Explainsupport for ASP.NET Asynchronous JavaScript and XML (AJAX) and the Javascript Object Notation (JSON) data format to allow WCF services to expose operations to AJAX clients.

WCF Discovery

Explainsupport to enable services to be discoverable at runtime in an interoperable way using the WS-Discovery protocol.

Routing
Explainthe routing service.


WCF Architecture

There are five layers:-
1)Application
2)Contracts
3)Service Runtime
4)Messaging
5)Activation and hosting

Contracts

Contracts layer are second layer of the wcf architecture. Developer will directly use this contract to develop the service. We are also going to do the same now.

i) Service contract

-It explains  about the operation that service can provide.

ii) Data contract

- It explains  the custom data type which is exposed to the client and defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

iii) Message Contract

- Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

iv) Policies and Binding

- It  specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

Service Runtime

- It contains the behaviors that occur during runtime of service.
  • Error Behavior - Specifies what occurs, when internal error occurs on the service.
  • Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.
  • Throttling Behavior- Controls how many messages are processed.
  • Metadata Behavior - Tells how and whether metadata is available to outside world.
  • Instance Behavior - Specifies how many instance of the service has to be created while running.
  • Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.

Messaging

It is composed of channels and  channel is a component that processes a message in some way, for example, by authenticating a message. Channels are the core abstraction for sending message to and receiving message from an Endpoint and  set of channels is also known as a channel stack.t. Broadly we can categories channels as

  • Transport Channels: Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.
  • Protocol Channels: Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

Activation and Hosting

Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF serv ice can be hosted by following mechanism

  • IIS Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.
  • Windows Activation Service (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.
  • Self-Hosting WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.
  • Windows Service WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM)
Difference between WCF and Web service 
 Web service is a part of WCF. WCF provides  much more flexibility and portability to develop a service when comparing to web service.


Features Web Service WCF
Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions

WCF Contracts

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.

There are four Contracts:
  • Service contracts: Define  which operations the client can perform on the service. Service contracts are the subject of the next chapter, but are used extensively in every chapter in this book.
  • 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 you can easily define explicit opt-in data contracts for custom types
  • 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 you have to comply with.

WCF Service

A service-oriented application (SOA) aggregates services into a single logical application similar to the way a component-oriented application aggregates components or an object-oriented application aggregates objects and ervice-orientation (SO) is an abstract set of principles and best practices for building SO applications .The services can be local or remote, developed by multiple parties using any technology, versioned independently, and even execute on different timelines. Inside a service, you will find concepts such as languages, technologies, platforms, versions, and frameworks, yet between services, only prescribed communication patterns are allowed.The client of a service is merely the party consuming its functionality. The client can be literally anythinga Windows Forms class, an ASP.NET page, or another service
Clients and services interact by sending and receiving messages. Messages may transfer directly from client to service or via an intermediary. With WCF, all messages are SOAP messages.the messages are independent of transport protocolsunlike Web services, WCF services may communicate over a variety of transports, not just HTTP. WCF clients may interoperate with non-WCF services, and WCF services can interact with non-WCF clients


Services' Execution Boundaries
 
With WCF, the client never interacts with the service directly, even when dealing with a local, in-memory service. The client always uses a proxy to forward the call to the service. The proxy exposes the same operations as the service, plus some proxy-management methods. WCF allows the client to communicate with the service across all execution boundaries.

 
 
Service contracts


The ServiceContractAttribute is defined as:
[AttributeUsage(AttributeTargets.Interface|AttributeTargets.Class,
                Inherited = false)]
public sealed class ServiceContractAttribute : Attribute
{
   public string Name
   {get;set;}
   public string Namespace
   {get;set;}
   //More members
}

Defining and implementing a service contract

[ServiceContract]
interface IMyContract
{
   [OperationContract]
   string show(string text);

   //Will not be part of the contract
   string show(string text);
}
class MyService : IMyContract
{
   public string show(string text)
   {
      return "Hello " + text;
   }
   public string show(string text)
   {
      return "Cannot call this method over WCF";
   }
} 
 
WCF  Addresses

WCF address provides two important elements:

1) The location of the service :-The location portion of the address indicates the name of the target machine, site, or network; a communication port, pipe, or queue; and an optional specific path or URI. A URI is a Universal Resource Identifier, and can be any unique string, such as the service name or a GUID.

2) The transport protocol or transport schema used to communicate with the service. 
 
WCF transport schemas
 
WCF 1.0 supports the following transport schemas
1)HTTP
2)TCP
3)Peer network
4)IPC (Inter-Process Communication over named pipes)
5)MSMQ
Addresses always have the following format:
[base address]/[optional URI] The base address is always in this format:
[transport]://[machine or domain][:optional port] EXAMPLE- http://localhost:8001 http://localhost:8001/MyService net.tcp://localhost:8002/MyService net.pipe://localhost/MyPipe net.msmq://localhost/private/MyService The way to read an address such as
http://localhost:8001  is like this: "Using HTTP, go to the machine called localhost, where on port 8001 someone is waiting for my calls."
If there is also a URI such as:
http://localhost:8001/MyService
http://localhost:8001/MyService
then the address would read as follows: "Using HTTP, go to the machine called localhost, where on port 8001 someone called

MyService is waiting for my calls."

1) HTTP Addresses:
HTTP addresses use http for transport, and can also use https for secure transport. You typically use HTTP addresses with outward-facing
Internet-based services, and can specify a port such as:
http://localhost:8001
When the port number is unspecified, it defaults to 80. Similar to TCP addresses, two HTTP addresses from the same host can share a port, even on the same machine.


2)TCP
TCP addresses use net.tcp for the transport, and typically include a port number such as:
net.tcp://localhost:8002/MyService When a port number is not specified, the TCP address defaults to port 808: net.tcp://localhost/MyService It is possible for two TCP addresses (from the same host, which will be discussed more later on in this chapter) to share a port: net.tcp://localhost:8002/MyService net.tcp://localhost:8002/MyOtherService 

3) IPC Addresses (Inter-Process Communication over named pipes)
 
IPC addresses use net.pipe for transport, to indicate the use of the Windows named pipe mechanism. In WCF, services that use named pipes can only accept calls from the same machine. Consequently, you must specify either the explicit local machine name or localhost for the machine name, followed by a unique string for the pipe name:
net.pipe://localhost/MyPipe 

4) MSMQ Addresses

MSMQ addresses use net.msmq for transport, to indicate the use of the Microsoft Message Queue (MSMQ). You must specify the queue name. When you're dealing with private queues, you must specify the queue type, but that can be omitted for public queues:
net.msmq://localhost/private/MyService net.msmq://localhost/MyService  

5) Peer Network Address

Peer network addresses use net.p2p for transport, to indicate the use of the Windows peer network transport. You must specify the peer network name as well as a unique path and port. Using and configuring peer networks is beyond the scope of this book, and you will see very little mention of peer networks in subsequent chapters.

WCF Bindings

A binding explains  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 defines nine standard bindings:

Basic binding: Defined 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: Defined 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: Defined 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. Peer networking is beyond the scope of this book since it requires an understanding of grid topology and mesh computing strategies.

IPC binding: Defined 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: Defined 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: Defined by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

Duplex WS binding: Defined 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: Defined by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls. MSMQ integration binding
defined by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.


WCF Hosting

WCF service  has to be hosted in windows process called as host process. Single host process can host multiple servers and same service type can be hosted in multiple host process
There are mainly four different way of hosting the WCF service.
1)IIS hosting
2)Self hosting
3)Windows Activation Service
4)Windows Service


The WCF host architecture

The WCF context is conceptually similar to the Enterprise Services context or the .NET context-bound object context Multiple hosting and protocols supported by WCF. Microsoft has introduced the WCF concept in order to make distributed application development and deployment simple.


Hosting Environment Supported protocol
Windows console and form application HTTP,net.tcp,net.pipe,net.msmq
Windows service application (formerly known as NT services) HTTP,net.tcp,net.pipe,net.msmq
Web server IIS6 http, wshttp
Web server IIS7 - Windows Process Activation Service (WAS) HTTP,net.tcp,net.pipe,net.msmq

A summary of hosting options and supported features. 
 
Feature Self-Hosting IIS Hosting WAS Hosting
Executable Process/ App Domain Yes Yes Yes
Configuration App.config Web.config Web.config
Activation Manual at startup Message-based Message-based
Idle-Time Management No Yes Yes
Health Monitoring No Yes Yes
Process Recycling No Yes Yes
Management Tools No Yes Yes


WCF  Channels  Working

We can  use channels directly to invoke operations on the service without ever resorting to using a proxy class.

TheChannelFactory<T> class:  

The ChannelFactory<T> class enables we to create a proxy on the fly.

public class contractexample
{
   public Type ContractType
   {get;set;}
   //More members
}

public class ServiceEndpoint
{
   public ServiceEndpoint(contractexample contract,Binding binding,EndpointAddress address);
   public EndpointAddress Address
   {get;set;}
   public Binding Binding
   {get;set;}
   public contractexample Contract
   {get;}
   //More members
}

public abstract class ChannelFactory : ...
{
   public ServiceEndpoint Endpoint
   {get;}
   //More members
}
public class ChannelFactory<T> : ChannelFactory,...
{
   public ChannelFactory(ServiceEndpoint endpoint);
   public ChannelFactory(string configurationName);
   public ChannelFactory(Binding binding,EndpointAddress endpointAddress);
   public static T CreateChannel(Binding binding,EndpointAddress endpointAddress);
   public T CreateChannel( );
   //More Members
} 
 
we  pass  the constructor of ChannelFactory<T> with the endpointeither the endpoint name from the client config file, or the binding and address objects, or a ServiceEndpoint object.Use the CreateChannel( ) method to obtain a reference to the proxy and use its methods. At the end  close the proxy by either casting it to IDisposable and calling the Dispose( ) method or to ICommunicationObject and calling the Close( ) method:
ChannelFactory<IMyContract> factory = new ChannelFactory<IMyContract>( ); IMyContract proxy1 = factory.CreateChannel( ); using(proxy1 as IDisposable) { proxy1.MyMethod( ); } IMyContract proxy2 = factory.CreateChannel( ); proxy2.MyMethod( ); ICommunicationObject channel = proxy2 as ICommunicationObject; Debug.Assert(channel != null); channel.Close( ); The InProcFactory Class
Class InProcFactory, defined as:
public static class InProcFactory { public static I CreateInstance<S,I>( ) where I : class where S : I; public static void CloseProxy<I>(I instance) where I : class; //More members } 
 
Implementing InProcFactory<T>

public static class InProcFactoryexample
{
   struct HostRecordstrustru
   {
      public HostRecordstrustru(ServiceHost host,string address)
      {
         Host = host;
         Address = address;
      }
      public readonly ServiceHost Host;
      public readonly string Address;
   }
   static readonly Uri BaseAddress = new Uri("net.pipe://localhost/");
   static readonly Binding NamedPipeBinding;
   static Dictionary<Type,HostRecordstrustru> m_Hosts = new Dictionary<Type,HostRecordstrustru>( );

   static InProcFactoryexample( )
   {
      NetNamedPipeBinding binding = new NetNamedPipeBinding( );
      binding.TransactionFlow = true;
      NamedPipeBinding = binding;
      AppDomain.CurrentDomain.ProcessExit += delegate
                                             {
                             foreach(KeyValuePair<Type,HostRecordstrustru> pair in m_Hosts)
                                                 {
                                                   pair.Value.Host.Close( );
                                                 }
                                              };
   }
   public static I CreateInstance<S,I>( ) where I : class
                                          where S : I
   {
      HostRecordstrustru HostRecordstrustru = GetHostRecordstrustru<S,I>( );
      return ChannelFactory<I>.CreateChannel(NamedPipeBinding,
                                          new EndpointAddress(HostRecordstrustru.Address));
   }
   static HostRecordstrustru GetHostRecordstru <S,I>( ) where I : class
                                           where S : I
   {
      HostRecordstru HostRecordstru;
      if(m_Hosts.ContainsKey(typeof(S)))
      {
         HostRecordstru = m_Hosts[typeof(S)];
      }
      else
      {
         ServiceHost host = new ServiceHost(typeof(S), BaseAddress);
         string address = BaseAddress.ToString() + Guid.NewGuid().ToString( );
         HostRecordstru = new HostRecordstru(host,address);
         m_Hosts.Add(typeof(S),HostRecordstru);
         host.AddServiceEndpoint(typeof(I),NamedPipeBinding,address);
         host.Open( );
      }
      return HostRecordstru;
   }
   public static void CloseProxy<I>(I instance) where I : class
   {
      ICommunicationObject proxy = instance as ICommunicationObject;
      Debug.Assert(proxy != null);
      proxy.Close( );
   }
}
 
WCF Endpoints

In WCF the relationship between Address, Contract and Binding is called Endpoint. The Endpoint is the fusion of Address, Contract and Binding. WCF formalizes this relationship in the form of an endpoint.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


Administrative Endpoint Configuration

Configuring an endpoint administratively requires placing the endpoints in the hosting process' config file. For example, given this service definition:

namespace endname
[ServiceContract] 
interface IMyContract 
{...} 
class MyService : IMyContract 
{...}
}   
Example

<system.serviceModel>
   <services>
      <service name = "MyNamespace.MyService">
         <endpoint
            address  = "http://localhost:8000/MyService/"
            binding  = "wsHttpBinding"
            contract = "MyNamespace.IMyContract"
         />
      </service>
   </services>
</system.serviceModel>

Multiple endpoints on the same service  
 
 <service name = "MyService">
   <endpoint
      address  = "http://localhost:8000/MyService/"
      binding  = "wsHttpBinding"
      contract = "IMyContract"
   />
   <endpoint
      address  = "net.tcp://localhost:8001/MyService/"
      binding  = "netTcpBinding"
      contract = "IMyContract"
    />
    <endpoint
      address  = "net.tcp://localhost:8002/MyService/"
      binding  = "netTcpBinding"
      contract = "IMyOtherContract"
    />
</service>
  
Service-side binding configuration 

<system.serviceModel>
   <services>
      <service name = "MyService">
         <endpoint
            address  = "net.tcp://localhost:8000/MyService/"
            bindingConfiguration = "TransactionalTCP"
            binding  = "netTcpBinding"
            contract = "IMyContract"
         />
         <endpoint
            address  = "net.tcp://localhost:8001/MyService/"
            bindingConfiguration = "TransactionalTCP"
            binding  = "netTcpBinding"
            contract = "IMyOtherContract"
         />
      </service>
   </services>
   <bindings>
      <netTcpBinding>
         <binding name = "TransactionalTCP"
            transactionFlow = "true"
         />
      </netTcpBinding>
   </bindings>
</system.serviceModel>
 
Service-side programmatic endpoint configuration

ServiceHost host = new ServiceHost(typeof(MyService));
Binding wsBinding  = new WSHttpBinding( );
Binding tcpBinding = new NetTcpBinding( );
host.AddServiceEndpoint(typeof(IMyContract),wsBinding,
                        "http://localhost:8000/MyService");
host.AddServiceEndpoint(typeof(IMyContract),tcpBinding,
                        "net.tcp://localhost:8001/MyService");
host.AddServiceEndpoint(typeof(IMyOtherContract),tcpBinding,
                        "net.tcp://localhost:8002/MyService");
host.Open( );
</system.serviceModel> 
 
AddServiceEndpoint( )-It adds a service endpoint to the hosted service with a specified contract, binding, and endpoint address.


First WCF Service

WCF programming model support 3 styles of programming :
  1. Declarative programming, in which we can   define attributes
  2. Imperative programming, in which we work with the WCF object model in code
  3. Configuration-based programming, in which we  define  behavior in application configuration files
Service programs : In it defines four element
  1. Contract definitions: A service  have at least one service contract, and it might contain multiple service contracts, data contracts, or message contracts.
  2. Implementation code: The service contracts in a service need code to implement their service operations.
  3. Hosting code:  Some code is needed to create and start the service.
  4. Endpoint definitions:  One or more address "binding" contract endpoints must be declared.
Before Starting :
This example require the following packages to be installed on your system:
  1. .net framework 3.0 RC1
  2. Windows SDK RC1
Application divided into 3 parts :
A.      Developing the Server application
  • Step 1 : Create the application
  • Step 2 : Create the Service Contracts
  • Step 3 : Create the Service Implementation Code
  • Step 4 : Create the Service Host
  • Step 5 : Create the Service Configurations
B.      Publish the Service MetaData
C.      Create .net Based Client Application
 
A) Developing the Server application

Step 1 : Create the application
  1. Open  your development environment and create a new C# console application project named server.
  2. Add reference to the System.ServiceModel.dll , then add reference to the System.ServiceModel namespace
  3. Change the name space to EgyAntiques.Store  as the
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
 
namespace EgyAntiques.Store
{
 
}
Step 2 : Create the Service Contracts
  1. Define the interface that will serve as a contract for our application , decorate your interface with ServiceContract Attribute
  2. Define 2 methods signature as in the following code , those methods will serve as the contract operations , decorate your methods with the OperationContract attribute
   [ServiceContract]
    public interface IAntiques
    {
        [OperationContract]
        string DisplayAntiquesList();
 
        [OperationContract]
        double GetAntiquePrice(int antiqueID);
    }
Step 3 : Create the Service Implementation Code
  1. Define AntiquesService Class which will implement the IAntiques interface
  2. Provide Implementation for the 2 methods as in the following code
    public class AntiquesService : IAntiques
    {
        public string DisplayAntiquesList()
        {
            string str = " 1.A \n 2.B \n 3.c \n 4.D";
            return str;
        }
 
        public double GetAntiquePrice(int antiqueID)
        {
            switch (antiqueID)
            {
                case 1:
                    return 100.05;
                    break;
                case 2:
                    return 150.00;
                    break;
                case 3:
                    return 340.23;
                    break;
                case 4:
                    return 1000;
                    break;
                default:
                    return 00.00;
                    break;
            }
        }
    }
Step 4 : Create the Service Host Add  main method to the class ,which will create a new ServiceHost object and open this host , the host will not run untill we specify the endpoints  that will allow the other services to communicate with our AntiquesService , this part we will do using configuration files. 
        static void Main(string[] args)
        {
            ServiceHost sh = new ServiceHost(typeof(AntiquesService));
           
            try
            {
                sh.Open();
                Console.WriteLine("EgyAntiques Store Service opened successfully");
                Console.WriteLine("Press Enter to terminate EgyAntiques Store Service");
                Console.ReadLine();
            }
            finally
            {
                sh.Close();
}
Step 5 : Create the Service Configurations
  1. Build your project and make sure that it successfully built
  2. Open the Service Configuration Editor (Tool come with Windows SDK ) and load the application file , from File Open à Executable - Browse for Server.exe
Click create new service , and specify the service type as “EgyAntiques.Store.AntiquesService”


 
4      Specify the Service Contract for the service as “EgyAntiques.Store.IAntiques 




5.       Set the communication mode for HTTP


6.       Set the method of interoperability to Advanced Web service Interoperability , and set the communication Simplex Communication

7.       Left the address field for your endpoint empty in this case the WCF will search for base address for the service and will consider this address as address for the endpoint
8.       Click finish , you should see the following result by now


9.       Now click from the left pane the Host Icon , then click New to add new base address for your service , then set the address for your service to  http://r4r-03/service


 

10.   Expand the Endpoints from the left pane and select your end point , then in the name field write “ep1” this is the name for your endpoint in will be used to reference this endpoint configuration from inside code


B . Publish the Service MetaData
1.       Expand from the left pane the Advanced node , then click Service Behaviors node  and click New Service Behavior Configuration from the right pane 
2.       Set the BehaviorConfiguration name to “MetaDataBehavior” , and click add to add Behavior element , then select ServiceMetaData
3.       Select the serviceMetaData from the left pane , on the right pane set the HttpGetEnabled to true and the HttpGetUrl to http://r4r-03/service
4.       Now Select the EgyAntiques.Store.AntiqueService node from the left pane then set the Behavior Configuration in the right pane to your Behavior name “MetaDataBehavior” 
 
6.       Now you can run your service , it should run ok without any errors , if everything is alright you’ll see this screen  :

C . Create .net Based Client Application
1.   Open command shell and navigate to the required folder you need the tool to generate the files in , then write the following command and hit enter:
You should see the following result , and if you got to the folder you had specified for the tool you will find 2 files (1) AntiquesService.cs (2) output.config
2.   Now create new console project name it “client”, set the name space to “EgyAntiques.Store” , then add reference to the “System.ServiceModel.dll” , finally add the generated files to your project “AntiquesService.cs” and rename the configuration file to “app.config” then add it to the project ,the result should look like that
3.   You only need to create proxy object from your generated proxy , then call your service methods from the proxy , here is the code you need to add to the main method of your client :
             Console.WriteLine("Please press enter to get the list of our antiques :");
            Console.ReadLine();
            AntiquesClient client = new AntiquesClient("ep1");
            Console.Write(client.DisplayAntiquesList());
            Console.WriteLine("\n\n\nPlease select your Antique # to know it's price :");
            Console.WriteLine("Your Antique Price is : "+client.GetAntiquePrice(int.Parse(Console.ReadLine())));
            Console.WriteLine("\npress enter to terminate the program ... ");
            Console.ReadLine();
4.    Save and compile your application , check if there is errors , if successfully built , run the server application , then run your client application , you should get the following result



CODE FOR SERVER

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace EgyAntiques.Store
{
    [ServiceContract]

    public interface IAntiques
    {

        [OperationContract]

        string DisplayAntiquesList();



        [OperationContract]

        double GetAntiquePrice(int antiqueID);

    }
    public class AntiquesService : IAntiques
    {

        public string DisplayAntiquesList()
        {

            string str = " 1.A\n 2.B \n 3.C \n 4.D";

            return str;

        }



        public double GetAntiquePrice(int antiqueID)
        {

            switch (antiqueID)
            {

                case 1:
                    return 100.05;
                    break;
                case 2:
                    return 150.00;
                    break;
                case 3:
                    return 340.23;
                    break;
                case 4:
                    return 1000;
                    break;
                default:
                    return 00.00;
                    break;


            }

        }
        static void Main(string[] args)
        {

            ServiceHost sh = new ServiceHost(typeof(AntiquesService));



            try
            {

                sh.Open();

                Console.WriteLine("EgyAntiques Store Service opened successfully");

                Console.WriteLine("Press Enter to terminate EgyAntiques Store Service");

                Console.ReadLine();

            }

            finally
            {

                sh.Close();

            }
        }
    }
} 
 
CODE FOR CLIENT
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ServiceModel;

namespace EgyAntiques.Store
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please press enter to get the list of our antiques :");

            Console.ReadLine();

            AntiquesClient client = new AntiquesClient("ep1");

            Console.Write(client.DisplayAntiquesList());

            Console.WriteLine("\n\n\nPlease select your Antique # to know it's price :");

            Console.WriteLine("Your Antique Price is : " + client.GetAntiquePrice(int.Parse(Console.ReadLine())));

            Console.WriteLine("\npress enter to terminate the program ... ");

            Console.ReadLine();
        }
    }
}

Data Contract Hierarchy
Data contract class can  be the subclass of another data contract class. Since  the Data Contract attribute is not inheritable so WCF requires that every level in the class hierarchy explicitly opt in for a given data contract.


[DataContract]
class Contact
{
   [DataMember]
   public string FtName;

   [DataMember]
   public string LName;
}
[DataContract]
class Customer : Contact
{
   [DataMember]
   public int CNumber;
} 
 
1.Known Types
The KnownType attribute allows you to designate acceptable subclasses for the data contract:

[DataContract]
[KnownType(typeof(Customer))]
class Contact
{...}

[DataContract]
class Customer : Contact
{...} 
 
The KnownType attribute includes the subclass in the metadata so that the client will have its own definition of the subclass and will be able to pass the subclass instead of the base class. Using the base class, all contracts and operations are  affected by The KnownType attribute , across all services and endpoints on the host side and  allowing it to accept subclasses instead of base classes. If the client also applies the KnownType attribute on its copy of the base class, it can in turn receive the known subclass back from the service.

2. Service Known Types

WCF also provides the ServiceKnownTypeAttribute, defined as:

[AttributeUsage(AttributeTargets.Interface|
                AttributeTargets.Method   |
                AttributeTargets.Class,
                AllowMultiple = true)]
public sealed class ServiceKnownTypeAttribute : Attribute
{
   public ServiceKnownTypeAttribute(Type type);
   //More members
}



Instead of using the KnownType 
attribute on the base data contract we  can apply the ServiceKnownType 
attribute on a specific operation on the service side. Then, only that operation 
(across all supporting services) can accept the known subclass:
 
[DataContract]
class Contact
{...}

[DataContract]
class Customer : Contact
{...}

[ServiceContract]
interface IContactManager
{
   [OperationContract]
   [ServiceKnownType(typeof(Customer))]
   void AddContact(Contact contact);

   [OperationContract]
   Contact[] GetContacts();
} 

3. Multiple Known Types
Tthe KnownType and the ServiceKnownType attributes both  can be applied  multiple times to inform WCF about as many known types as required:

[DataContract]
class Contact
{...}

[DataContract]
class Customer : Contact
{...}

[DataContract]
class Person : Contact
{...}

[ServiceContract]
[ServiceKnownType(typeof(Customer))]
[ServiceKnownType(typeof(Person))]
interface IContactManager
{...}

4. Configuring Known Types

The main disadvantage  of the known types attributes is that they require the service or the client to know in advance about all possible subclasses the other party may want to use. Adding a new subclass necessitates changing the code, recompiling, and redeploying. To alleviate this, WCF lets you configure the known types in the service's or client's config file. 
<system.runtime.serialization>
   <dataContractSerializer>
      <declaredTypes>
         <add type = "Contact,Host,Version=1.0.0.0,Culture=neutral,
                                      PublicKeyToken=null">
       <knownType type = "Customer,MyClassLibrary,Version=1.0.0.0,
                          Culture=neutral,PublicKeyToken=null"/>
         </add>
      </declaredTypes>
   </dataContractSerializer>
</system.runtime.serialization> 
 
5. Object and Interfaces
The base type of a data contract class or a struct can be an interface:

Interface IContact
{
   string FirstName
   {get;set;}
   string LastName
   {get;set;}
}
[DataContract]
class Contact : IContact
{...} 
 
You can use such a base interface 
in your service contract or as a data member in a data contract if you use the 
ServiceKnownType attribute to designate the actual data type:
 
[ServiceContract]
[ServiceKnownType(typeof(Contact))]
interface IContactManager
{
   [OperationContract]
   void AddContact(IContact contact);

   [OperationContract]
   IContact[] GetContacts();
}
 
Data Contract Equivalence
Two data contracts are considered equivalent  if they have the same wire representation means  if they have the same schema. This can be the case if they define the same type (but not necessarily the same version of the type) or if the two data contracts refer to two different types with the same data contract and data member names. Equivalent data contracts are interchangeable: WCF will let any service that was defined with one data contract operate with an equivalent data contract.
these two data contracts are equivalent
[DataContract]
struct Contact
{
   [DataMember]
   public string FirstName;

   [DataMember]
   public string LastName;
}
[DataContract(Name = "Contact")]
struct Person
{
   [DataMember(Name = "FirstName")]
   public string Name;

   [DataMember(Name = "LastName")]
   public string Surname;
}
 
Serialization Order

Equivalent data contracts must serialize and deserialize their members in the same order
when serializing a Customer instance, defined as:

[DataContract]
class Contact
{
   [DataMember]
   public string FName;

   [DataMember]
   public string LName;
}
[DataContract]
class Customer : Contact
{
   [DataMember]
   public int CNumber;
 }

the members will be serialized in the following order: FName, LName, CNumber.

The problem  is that combining data contract hierarchy with aliasing contracts and members might break the serialization order

To resolve this conflict,we  provide WCF with the order of serialization by setting the Order property of the DataMember attribute. The Order property defaults to -1, meaning the default WCF ordering, but you can assign to it values indicating the required order:

[DataContract(Name = "Customer")]
public class Person
{
   [DataMember(Name = "FirstName",Order = 1)]
   public string Name;

   [DataMember(Name = "LastName",Order = 2)]
   public string Surname;

   [DataMember,Order = 3)]
   public int CustomerNumber;
}
 
Data Contract Versioning

WCF needs to enable both backward and forward compatibility, without even sharing types or version information.
 There are three main versioning scenarios:
  • New members
  • Missing members
  • Round tripping, where a new version is passed to and from an old version, requiring both backward and forward compatibility
By default, data contracts are version tolerant and will silently ignore incompatibilities.

1. New Members

Both the service and the client can accept data with new members that were not part of original contract when the new members can  simply be ignored by DataContractSerializer when deserializing the type. For example, the service may be built against this data contract:
[DataContract]
struct Contact
{
   [DataMember]
   public string FirstName;

   [DataMember]
   public string LastName;
}

and yet the client may send it this data contract instead:
[DataContract]
struct Contact
{
   [DataMember]
   public string FirstName;

   [DataMember]
   public string LastName;

   [DataMember]
   public string Address;
} 
 
2. Missing Members

Missing members are initialized to their default value

////////////////////////// Service Side //////////////////////////////
[DataContract]
struct Contact
{
   [DataMember]
   public string FName;

   [DataMember]
   public string LName;

   [DataMember]
   public string Address;
}

[ServiceContract]
interface IContactManager
{
   [OperationContract]
   void AddContact(Contact contact);
   ...
}

class ContactManager : IContactManager
{
   public void AddContact(Contact contact)
   {
      Trace.WriteLine("First name = " + contact.FirstName);
      Trace.WriteLine("Last name = " + contact.LastName);
      Trace.WriteLine("Address = " + (contact.Address ?? "Missing"));
      ...
   }
   ...
}
/////////////////////////// Client Side //////////////////////////////
[DataContract]
struct Contact
{
   [DataMember]
   public string FirstName;

   [DataMember]
   public string LastName;
}

Contact contact = new Contact( );
contact.FirstName = "Kamal";
contact.LastName = "Ashish";

ContactManagerClient proxy = new ContactManagerClient( );
proxy.AddContact(contact);

proxy.Close( );
 
3. Versioning Round-Trip

The versioning tolerance techniques described  so far for ignoring new members and defaulting missing ones are suboptimal. The versioning tolerance techniques enable a point-to-point client-to-service call but have no support for a wider-scope pass-through scenario.


 

  
Data Contract Enumerations

Enumerations are always serializable by definition. When you explain  a new enum, there is no need to apply the DataContract attribute on it, and you can freely use it in a data contract

Using an enum in a data contract

enum ContactType
{
   EName,
   EmpPost,
   EmpAddress
}
[DataContract]
struct Contact
{
   [DataMember]
   public ContactType ContactType;
   [DataMember]
   public string FName;
   [DataMember]
   public string LName;
}
 
Delegates and Data Contracts

All delegate definitions are compiled into serializable classes, and so in theory your data contract types could contain delegates as member variables:

[DataContract]
class A
{
   [DataMember]
   public EventHandler ME;
}
 
or even as events
[DataContract]
class A
{
   [field:DataMember]
   public event EventHandler ME;
}
 
Data Sets and TablesData 
 
The raw DataSet and DataTable types are serializable, marked with the Serializable attribute:

[Serializable]
public class DataSet : ...
{...}

[Serializable]
public class DataTable : ...
{...}
 
Type-safe data set and data table

[Serializable]
public partial class Exampleofdataset : DataSet
{
   public ContactsDataTable Contacts
   {get;}

   [Serializable]
   public partial class ContactsDataTable : DataTable,IEnumerable
   {
      public void AddContactsRow(ContactsRow row);
      public ContactsRow AddContactsRow(string FirstName,string LastName);
      //More members
   }

   public partial class ContactsRow : DataRow
   {
      public string FName
      {get;set;}

      public string LName
      {get;set;}
      //More members
   }
   //More members
}
public partial class ContactsTableAdapter : Component
{
   public file Exampleofdataset.ContactsDataTable GetData( );
   //More members
}
 
Data Contract Generics

Generics are specific to .NET, and using them would avoid  the service-oriented nature of WCF and  use bounded generic types in your data contracts, as long as you specify the type parameters in the service contract and as long as the specified type parameters have valid data contracts.We  cannot define WCF contracts that rely on generic type parameters.
 
Using bounded generic types Example
 
[DataContract]
class MyClass<T>
{
   [DataMember]
   public T m_MyMember;
}

[ServiceContract]
interface IMyContract
{
   [OperationContract]
   void MyMethod(MyClass<int> obj);
}
 
Collections

Acollection is any type that supports the IEnumerable or IEnumerable<T> interfaces. All of the built-in collections in .NET, such as the array, the list, and the stack support these interfaces.
A data contract can include a collection as a data member, or a service contract can define operations that interact with a collection directly. Because .NET collections are .NET-specific, WCF cannot expose them in the service metadata, yet because they are so useful, WCF offers dedicated marshaling rules for collections.

Example:
ServiceContract]
interface IContactManager
{
   [OperationContract]
   IEnumerable<Contact> GetContacts( );
   ...
}
class ContactManager : IContactManager
{
   List<Contact> m_Contacts = new List<Contact>( );

   public IEnumerable<Contact> GetContacts( )
   {
      return m_Contacts;
   }
   ...
} 
 
Data Sets and Tables 

The raw DataSet and DataTable types are serializable, marked with the Serializable attribute:

[Serializable]
public class DataSet : ...
{...}

[Serializable]
public class DataTable : ...
{...}
 
We can define valid service contracts that accept or return data tables or data sets: 
 
[DataContract]
struct Contact
{...}

[ServiceContract]
interface IContactManager
{
   [OperationContract]
   void AddContact(Contact contact);

   [OperationContract]
   void AddContacts(DataTable contacts);

   [OperationContract]
   DataTable GetContacts( );
}
 
Example of Type-safe data set and data table

[Serializable]
public partial class MyDataSet : DataSet
{
   public ContactsDataTable Contacts
   {get;}

   [Serializable]
   public partial class ContactsDataTable : DataTable,IEnumerable
   {
      public void AddContactsRow(ContactsRow row);
      public ContactsRow AddContactsRow(string FirstName,string LastName);
      //More members
   }

   public partial class ContactsRow : DataRow
   {
      public string FName
      {get;set;}

      public string LName
      {get;set;}
      //More members
   }
   //More members
}
public partial class ContactsTableAdapter : Component
{
   public file MyDataSet.ContactsDataTable GetData( );
   //More members
} 
 
DataTableHelper:-

It requires is a converter from a data row in the table to the data contract. DataTableHelper also adds some compile-time and runtime type-safety verification

Exapmle: Using DataTableHelper

[DataContract]
struct Contact
{
   [DataMember]
   public string FName;

   [DataMember]
   public string LNamee;
}
[ServiceContract]
interface IContactManager
{
   [OperationContract]
   Contact[] GetContacts( );
   ...
}
class ContactManager : IContactManager
{
   public Contact[] GetContacts( )
   {
      ContactsTableAdapter adapter = new ContactsTableAdapter( );
      MyDataSet.ContactsDataTable contactsTable = adapter.GetData( );

      Converter<MyDataSet.ContactsRow,Contact> converter;
      Converter = delegate(MyDataSet.ContactsRow row)
                  {
                     Contact contact = new Contact( );
                     contact.FName = row.FName;
                     contact.LNamee  = row.LNamee;
                     return contact;
                  };

      return DataTableHelper.ToArray(contactsTable,converter);
   }
   //Rest of the implementation
} 
 
DataTableHelper.ToArray ( )

DataTableHelper used for  add some type safety . at compile time, DataTableHelper places constraints on the type parameter R to be a data row and  at runtime, the ToArray( ) method returns an empty array if the table is empty.

ataTableHelper.ToArray( ) use the myCollection helper class to invoke the converter on every row in the table, converting every row to a single Contact and returning the resulted array and It verifies that the type parameter T is decorated either with the DataContract attribute or the Serializable attribute.

Instance Management

Instance management is the name for a set of techniques used by WCF to bind client requests to service instances, governing which service instance handles which client request.

Behaviors

A behavior is a local attribute of a  service that does not affect its communication patterns. Clients should be unaware of behaviors, and behaviors do not manifest themselves in the service's binding or published metadata.

Type of Behaviors

Two type of behaviors
1)ServiceBehaviorAttribute
2)OperationBehaviorAttribute


1)ServiceBehaviorAttribute

the ServiceBehavior attribute is used to configure the service instance mode.

Example  of The ServiceBehaviorAttribute used to configure instance context mode
public enum InstanceContextMode
{
   PerCall,
   PerSession,
   Single
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class ServiceBehaviorAttribute : Attribute,...
{
   public InstanceContextMode InstanceContextMode
   {get;set;}
   //More members
} 
 
2)OperationBehaviorAttribute

The OperationBehaviorAttribute is used to configure operation behaviors, and it  can be applied only on a method that implements a contract operation, never on the operation definition in the contract itself.

Per-Call Services

PerCall service instances are created  with every method call on the server side and destroyed also with every method call on the server side and When the service type is created for per-call activation, a service instance (the CLR object) exists only while a client call is in progress .Every client request gets a new dedicated service instance.
Per call activation works as given below-
  1. The client calls the proxy and the proxy forwards the call to the service.
  2. WCF creates a service instance and calls the method on it.
  3. if the object implements IDisposable, WCF calls IDisposable.Dispose( ) on it then  the method call returns, .
  4.  The proxy forwards the call to the service. when The client calls the proxy and
  5. WCF creates an object and calls the method on it.
Configuring Per-Call Services

To configure a service type as a per-call service, We apply the ServiceBehavior attribute with the InstanceContextMode property set to InstanceContextMode.PerCall:

[ServiceContract]
interface IMyContract
{...}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract
{...}
Per-call service and client Example

///////////////////////// Service code /////////////////////
[ServiceContract]
interface IMyContract
{
   [OperationContract]
   void operation( );
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract,IDisposable
{
   int flag = 0;

   MyService( )
   {
      Trace.WriteLine("MyService.MyService( )");
   }
   public void operation( )
   {
      flag++;
      Trace.WriteLine("Counter = " + flag);
   }
   public void Dispose( )
   {
      Trace.WriteLine("MyService.Dispose( )");
   }
}
///////////////////////// Client code /////////////////////
MyContractClient proxy = new MyContractClient( );

proxy.operation( );
proxy.operation( );

proxy.Close( );

//Possible Output
MyService.MyService( )
Counter = 1
MyService.Dispose( )
MyService.MyService( )
Counter = 1
MyService.Dispose( ) 
 
Example of  Implementing a per-call service 
[DataContract]
class Exapmleofpercallservice
{...}

[ServiceContract]
interface IMyContract
{
   [OperationContract]
   void MyMethod(Exapmleofpercallservice stateIdentifier);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyPerCallService : IMyContract,IDisposable
{
   public void MyMethod(Exapmleofpercallservice stateIdentifier)
   {
      GetState(stateIdentifier);
      DoWork( );
      SaveState(stateIdentifier);
   }
   void GetState(Exapmleofpercallservice stateIdentifier)
   {...}
   void DoWork( )
   {...}
   void SaveState(Exapmleofpercallservice stateIdentifier)
   {...}
   public void Dispose( )
   {...}
}
 
Per-Session Services

Per service endpoint per proxy is the client session.
If the client creates another proxy to the same or a different endpoint then  that second proxy will be associated with a new instance and session.

Configuring Private Sessions

A session has three elements
1) behavior,
2} binding,
3) contract. 
 
The behavior part is used  for  that WCF will keep the service instance alive throughout the session and to direct the client messages to it. 
 
This local behavior  is created by setting the InstanceContextMode property of the ServiceBehavior attribute to InstanceContextMode.PerSession:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class MyService : IMyContract
{...}
 
Since InstanceContextMode.PerSession is the default value of the InstanceContextMode property, these definitions are equivalent:

class MyService : IMyContract
{...}

[ServiceBehavior]
class MyService : IMyContract
{...}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
class MyService : IMyContract
{...}
SessionMode.Allowed
 
SessionMode.Allowed is the default value of the property, so these definitions are equivalent:

[ServiceContract]
interface IMyContract
{...}

[ServiceContract(SessionMode = SessionMode.Allowed)]
interface IMyContract
{...}
 
Example  Per-session service and client
 
///////////////////////// Service code /////////////////////
[ServiceContract(SessionMode = SessionMode.Required)]
interface IMyContract
{
   [OperationContract]
   void operation( );
}
class MyService : IMyContract,IDisposable
{
   int flag= 0;
   MyService( )
   {
      Trace.WriteLine("MyService.MyService( )");
   }
   public void operation( )
   {
      flag++;
      Trace.WriteLine("Counter = " + flag);
   }
   public void Dispose( )
   {
      Trace.WriteLine("MyService.Dispose( )");
   }
}
///////////////////////// Client code /////////////////////
MyContractClient proxy = new MyContractClient( );
proxy.operation( );
proxy.operation( );
proxy.Close( );
//Output
MyService.MyService( )
Counter = 1
Counter = 2
MyService.Dispose( )
 
Callback reentrancy

If the single-threaded service instance tries to call back to its client, WCF will throw an InvalidOperationException to avoid a deadlock.Then  possible solutions is that   to configure the service for reentrancy. When configured for reentrancy, the service instance is still associated with a lock and only a single-threaded access is allowed. However, if the service is calling back to its client, WCF will silently release the lock first.

Example :- Configure for reentrancy to allow callbacks
[ServiceContract(CallbackContract = typeof(IMyContractCallback))]
interface IMyContract
{
   [OperationContract]
   void operation( );
}
interface IMyContractCallback
{
   [OperationContract]
   void OnCallback( );
}
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
class MyService : IMyContract
{
   public void operation( )
   {
      IMyContractCallback imcc = OperationContext.Current.
                                         GetCallbackChannel<IMyContractCallback>( );
      imcc.OnCallback( );
   }
}
 
Example :- One-way callbacks are allowed by default 
[ServiceContract(CallbackContract = typeof(IMyContractCallback))]
interface IMyContract
{
   [OperationContract]
   void operation( );
}
interface IMyContractCallback
{
   [OperationContract(IsOneWay = true)]
   void OnCallback( );
}
class MyService : IMyContract
{
   public void operation( )
   {
      IMyContractCallback imcc = OperationContext.Current.
                                         GetCallbackChannel<IMyContractCallback>( );
     imcc.OnCallback( );
   }
}
 
Defining and configuring a callback contract

We provide the  ServiceContract attribute with the type of the callback contract and the definition of the callback contract for define a service contract with a callback contract

Example
interface ISomeCallbackContract
{
   [OperationContract]
   void OnCallback( );
}

[ServiceContract(CallbackContract = typeof(ISomeCallbackContract))]
interface IMyContract
{
   [OperationContract]
   void operation1( );
} 
 
Duplex proxy

When we use such  a service endpoint whose contract defines a callback contract, then the client  use a proxy that will set up the bidirectional communication and pass the callback endpoint reference to the service. The proxy the client uses must derive from the specialized proxy class DuplexClientBase<T> .

Example of  DuplexClientBase<T>
public interface IDuplexContextChannel : IContextChannel
{
   InstanceContext CbInstance
   {get;set;}
   //More members
}
public abstract class DuplexClientBase<T> : ClientBase<T> where T : class
{
   protected DuplexClientBase(InstanceContext callbackContext);
   protected DuplexClientBase(InstanceContext callbackContext,
                              string EpName);
   protected DuplexClientBase(InstanceContext callbackContext,
                              Binding binding,
                              EndpointAddress remoteAddress);
   protected DuplexClientBase(object CbInstance);
   protected DuplexClientBase(object CbInstance,
                              string endpointConfigurationName);
   protected DuplexClientBase(object CbInstance,Binding binding,
                              EndpointAddress remoteAddress);

   public IDuplexContextChannel InnerDuplexChannel
   {get;}
   //More members
}
 
Tool-generated duplex proxy

When we use use SvcUtil or Visual Studio 2005 to create  a proxy class targeting a service with a callback contract then  the tools will create  a class that derives from DuplexClientBase<T>
partial class MyContractClient : DuplexClientBase<IMyContract>,IMyContract
{
   public MyContractClient(InstanceContext callbackContext) : base(callbackContext)
   {}

   public MyContractClient(InstanceContext callbackContext,string EpName) :
                                                 base(callbackContext,EpName)
   {}
   public MyContractClient(InstanceContext callbackContext,Binding binding,
                                                   EndpointAddress remoteAddress) :
                                        base(callbackContext,binding,remoteAddress)
   {}
   //More constructors

   public void operation( )
   {
      Channel.operation( );
   }
}
 
Client implementing the callback contract

class MyClient : IMyContractCallback,IDisposable
{
   MyContractClient mypro;

   public void CallService( )
   {
      InstanceContext cn = new Instancecn(this);
      mypro = new MyContractClient(cn);
      mypro.operation( );
   }
   public void OnCallback( )
   {...}

   public void Dispose( )
   {
      mypro.Close( );
   }
}

Operations in WCF

There  are three operations:-
1)Request-Reply Operations
2)One-Way Operations
3)Callback Operations

1)Request-Reply Operations

Request-Reply Operations implies the client issues a request in the form of a message, and blocks until it get the reply message. If the service does not respond within a default timeout of one minute, the  client will get a TimeoutException. Request-reply is the default operation mode. Programming against request-reply operations is simple enough and resembles programming using the classic client/server model. The returned response message containing the results or returned values is converted to normal method returned values. In addition, the proxy will throw an exception on the client side if there are any communication or service-side exceptions. With the exception of the NetPeerTcpBinding and NetMsmqBinding, all bindings support request-reply operations.

2)One-Way Operations

In One-Way operation mode, client will send a request to the server and does not care whether it is success or failure of service execution. There are cases when an operation has no returned values, and the client does not care about the success or failure of the invocation.There is no need to wait, till server execute.There is no return from the server side, it is one-way communication.Client will be blocked only for a moment till it dispatches its call to service. If any exception thrown by service will not reach the server.Client can continue to execute its statement, after making one-way call to server.
 
Configuring One-Way Operations

The OperationContract attribute offers the Boolean IsOneWay property:

[AttributeUsage(AttributeTargets.Method)]
public sealed class OperationContractAttribute : Attribute
{
   public bool a
   {get;set;}
   //More members
}
 
IsOneWay defaults to false, which means a request-reply operation (hence the WCF default). However, setting IsOneWay to TRue configures the method as a one-way operation:

[ServiceContract]
interface IMyContract
{
   [OperationContract(a = true)]
   void show( );
}

One-Way Operations and Sessionful Services

WCF design a sessionful contract with one-way operations:

[ServiceContract(SessionMode = SessionMode.Required)]
interface IMyContract
{
   [OperationContract(IsOneWay = true)]
   void show( )
}
 
Per-call services and one-way exceptions
 
In the case of a per-call service, when there is no transport session , if an exception takes place when invoking a one-way operation, the client is unaffected and can continue to issue calls on the same proxy instance:
[ServiceContract]
interface IMyContract
{
   [OperationContract(IsOneWay = true)]
   void operation1( );

   [OperationContract]
   void operation2( );
}

class MyService : IMyContract
{
   public void operation1( )
   {
     throw new Exception( );
   }
   public void operation2( )
   {}
}
//Client side when using basic binding:
MyContractClient proxy = new MyContractClient( );
proxy.operation1( );
proxy.operation2( );
proxy.Close( );
 
3)Callback Operations

 WCF supports allowing the service to call back to its clients.A service contract can have at most one callback contract. Callback operations are part of the service contract.It is up to the service contract to define its own callback contract.. Once defined, the clients are required to support the callback and provide the callback endpoint to the service in every call. To define a callback contract, the ServiceContract attribute offers the CallbackContract property of the type Type:

[AttributeUsage(AttributeTargets.Interface|AttributeTargets.Class)]
public sealed class ServiceContractAttribute : Attribute
{
   public Type CallbackContract
   {get;set;}
   //More members
}
 
Exapmle:
 
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
 
namespace CallbackApp
{
    public interface IMathCalculationCallback
    {
        [OperationContract]
        void calculate();
    }
 
    [ServiceContract(CallbackContract = typeof(IMathCalculationCallback))
    public interface IMathCalculation
    {
        [OperationContract]
        void LongCalculations(int nParam1, int nParam2);
    }
} 
 
Singleton Service


The singleton service is the ultimate sharable service. When you configure a service as a singleton, all clients are independently connected to the same single well-known

instance context and implicitly to the same instance inside, regardless of which endpoint  of the service they connect to.The singleton is created exactly once, when the

host is created, and lives forever: it is disposed of only when the host shuts down.


///////////////////////// Service code /////////////////////
[ServiceContract(SessionMode = SessionMode.Required)]
interface IMyContract
{
   [OperationContract]
   void operation1( );
}
[ServiceContract(SessionMode = SessionMode.NotAllowed)]
interface IMyOtherContract
{
   [OperationContract]
   void operation2( );
}
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
class MySingleton : IMyContract,IMyOtherContract,IDisposable
{
   int flag = 0;

   public MySingleton( )
   {
      Trace.WriteLine("MySingleton.MySingleton( )");
   }
   public void operation1( )
   {
      flag++;
      Trace.WriteLine("Counter = " + flag);
   }
   public voidoperation2( )
   {
      flag++;
      Trace.WriteLine("Counter = " + flag);
   }
   public void Dispose( )
   {
      Trace.WriteLine("Singleton.Dispose( )");
   }
}
///////////////////////// Client code /////////////////////
MyContractClient proxy1 = new MyContractClient( );
proxy1.operation1( );
proxy1.Close( );

MyOtherContractClient proxy2 = new MyOtherContractClient( );
proxy2.MyOtherMethod( );
proxy2.Close( );

//Output
MySingleton.MySingleton( )
Counter = 1
Counter = 2
 
Initializing a Singleton
//Service code
[ServiceContract]
interface IMyContract
{
   [OperationContract]
   void operation( );
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
class MySingleton : IMyContract
{
   int flag = 0;

   public int Counter
   {
      get
      {
         return flag;
      }
      set
      {
         flag = value;
      }
   }
   public void operation( )
   {
      flag++;
      Trace.WriteLine("Counter = " + Counter);
   }
}
//Host code
MySingleton singleton = new MySingleton( );
singleton.Counter = 100;

ServiceHost host = new ServiceHost(singleton);
host.Open( );
//Do some blocking calls then
host.Close( );

//Client code
MyContractClient proxy = new MyContractClient( );
proxy.operation( );
proxy.Close( );

//Outoput:
Counter = 101
 
Callback Connection Management

The callback mechanism provides  higher-level protocol for managing the connection between the service and the callback endpoint

Exapmle of Explicit callback connection management
[ServiceContract(CallbackContract = typeof(IMyContractCallback))]
interface IMyContract
{
   [OperationContract]
   void operation( );

   [OperationContract]
   void Connectoperation( );

   [OperationContract]
   void DisConnectoperation( );
}
interface IMyContractCallback
{
   [OperationContract]
   void OnCallback( );
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
class MyService : IMyContract
{
   static List<IMyContractCallback> m_Callbacks = new List<IMyContractCallback>( );
   public void Connectoperation( )
   {
      IMyContractCallback callback = OperationContext.Current.
                                         GetCallbackChannel<IMyContractCallback>( );
      if(m_Callbacks.Contains(callback) == false)
      {
         m_Callbacks.Add(callback);
      }
   }
   public void DisConnectoperation( )
   {
      IMyContractCallback callback = OperationContext.Current.
                                         GetCallbackChannel<IMyContractCallback>( );
      if(m_Callbacks.Contains(callback) == true)
      {
         m_Callbacks.Remove(callback);
      }
      else
      {
         throw new InvalidOperationException("Cannot find callback");
      }
   }
   public static void CallClients( )
   {
    Action<IMyContractCallback> invoke = delegate(IMyContractCallback callback)
                                         {
                                            callback.OnCallback( );
                                         };
      m_Callbacks.ForEach(invoke);
   }
   public void operation( )
   {...}
}

Duplex Factory
WCF also provides  DuplexChannelFactory<T>, which can be used for setting up duplex proxies programmatically

DuplexChannelFactory<T> is used as base class, ChannelFactory<T>, except its constructors expect either a callback instance or a callback context
public class DuplexChannelFactory<T> : ChannelFactory<T>
{
   public DuplexChannelFactory(object callback);
   public DuplexChannelFactory(object callback,string EPName);
   public DuplexChannelFactory(InstanceContext context,string EPName);

   public T CreateChannel(InstanceContext context);
   public static T CreateChannel(object callback,string EPName);
   public static T CreateChannel(InstanceContext context,string EPName);
   public static T CreateChannel(object callback,Binding binding,
                                EndpointAddress EPAddress);
   public static T CreateChannel(InstanceContext context,Binding binding,
                                 EndpointAddress EPAddress);
   //More members
} 
 
Throttling

Throttling enables  we  to restrain client connections and the load they place on  our service. Throttling enables we  to ignore  maxing out our service and the underlying resources it allocates and uses. If the settings we configure are exceeded, WCF will automatically place the pending callers in a queue and serve them out of the queue in orde,When throttling is engaged. While pending in the queue,If the client's call timeout expires, the client will get a TimeoutException. Throttling is done per service type; measn  it affects all instances of the service and all its endpoints. This is done by associating the throttle with every channel dispatcher the service uses.Throttling is a hosting and deployment aspect. When you design a service, make no assumptions about throttling configurationalways assume your service will bear the full brunt of the client's load.

Configuring Throttling

The following exapmle shows how to configure throttling in the host config file. Using the behaviorConfiguration tag,we add to your service a custom behavior that sets throttled values.
<system.serviceModel>
   <services>
      <service name = "MyService" behaviorConfiguration = "ThrottledBehavior">
         ...
      </service>
   </services>
   <behaviors>
      <serviceBehaviors>
         <behavior name = "ThrottledBehavior">
            <serviceThrottling
               maxConcurrentCalls     = "100"
               maxConcurrentSessions  = "454"
               maxConcurrentInstances = "426"
            />
         </behavior>
      </serviceBehaviors>
   </behaviors>
</system.serviceModel> 
 
Reading throttled values

With the help of service developers for diagnostic and analytical purposes,The throttled values can be read and the service instance can access its throttled properties from its dispatcher at run time

The host base class ServiceHostBase offers the read-only ChannelDispatchers property:

public abstract class ServiceHostBase : CommunicationObject,...
{
   public ChannelDispatcherCollection ChannelDispatchers
   {get;}
   //More members
}

ChannelDispatchers is a strongly typed collection of ChannelDispatcherBase objects:

public class ChannelDispatcherCollection :
 
Throttled Connections in the Binding
 
 Both the NetTcpBinding and the NetNamedPipeBinding offer the MaxConnections property:When use the TCP and give name-pipe bindings and  we  can also configure the maximum connection number for a particular endpoint in the binding itself
 
SynchronizedCollection<ChannelDispatcherBase> 
public class NetTcpBinding : Binding,...
{
   public int MaxConnections 
   {get;set;}
}
public class NetNamedPipeBinding : Binding,...
{
   public int MaxConnections 
   {get;set;}
}
On the host side, you can set that property either programmatically or by using a config file:

<bindings>
   <netTcpBinding>
      <binding name = "TCPThrottle" MaxConnections  = "25"/>
   </netTcpBinding>
</bindings>
 
MaxConnections  defaults to 10. When both a binding-level throttle and a service-behavior throttle sets the max connection value, WCF chooses the lesser of the two.

The DuplexChannelFactory<T,C> class

DuplexChannelFactory<T> is a base class, ChannelFactory<T>, except its constructors expect either a callback instance or a callback context. The use of object for the callback instance and the lack of type safety. Similar to fixing up the DuplexClientBase<T> class.
public class DuplexChannelFactory<T,C> : DuplexChannelFactory<T> where T : class
{
   static DuplexChannelFactory( )
   {
      DuplexClientBase<T,C>.VerifyCallback( );
   }

   public static T CreateChannel(C callback,string EPName)
   {
      return DuplexChannelFactory<T>.CreateChannel(callback,EPName);
   }
   public static T CreateChannel(InstanceContext<C> context,string EPName)
   {
      return DuplexChannelFactory<T>.CreateChannel(context.Context,EPName);
   }
   public static T CreateChannel(C callback,Binding binding,
                                 EndpointAddress endpointAddress)
   {
      return DuplexChannelFactory<T>.CreateChannel(callback,binding,
                                                                 endpointAddress);
   }
   public static T CreateChannel(InstanceContext<C> context,Binding binding,
                                 EndpointAddress endpointAddress)
   {
      return DuplexChannelFactory<T>.CreateChannel(context,binding,
                                                                  endpointAddress);
   }
   public DuplexChannelFactory(C callback) : base(callback)
   {}
   public DuplexChannelFactory(C callback,string EPName):
                                              base(callback,EPName)
   {}
   public DuplexChannelFactory(InstanceContext<C> context,string EPName) :
                                                 base(context.Context,EPName)
   {}
   //More constructors
} 
 
Adding duplex support to InProcFactory

public static class InProcFactory
{
   public static I CreateInstance<S,I,C>(C callback) where I : class
                                                     where S : class,I
   {
      InstanceContext<C> context = new InstanceContext<C>(callback);
      return CreateInstance<S,I,C>(context);
   }
   public static I CreateInstance<S,I,C>(InstanceContext<C> context)
                                                        where I : class
                                                        where S : class,I
   {
      HostRecord hostRecord = GetHostRecord<S,I>( );
      return  DuplexChannelFactory<I,C>.CreateChannel(
                 context,NamedPipeBinding,new EndpointAddress(hostRecord.Address));
   }
   //More members
}
//Sample client
IMyContractCallback callback = new MyClient( );

IMyContract proxy = InProcFactory.CreateInstance
                             <MyService,IMyContract,IMyContractCallback>(callback);
proxy.DoSomething( );
InProcFactory.CloseProxy(proxy);
 
Transactions in WCF

Transaction  is   a   building robust, high-quality service-oriented applications. Transactions ensure that a group of related operations occur as a single atomic unit. In other words, every operation in the unit must either all succeed or all fail..WCF provides simple, declarative transaction support for service developers, enabling you to configure parameters such as enlistment and voting, all outside the scope of your service.WCF provides a centralized transaction system that you can use to handle transaction operations for you.
The WCF programming model create  transactions very easy to use. You group operations into a transaction scope. This scope defines the atom of a transaction. The following pseudo code demonstrates this:
Using(TransactionScope transcope = new 
      TransactionScope())
   {
       Service1.submitRequest(solution);
       Service2.submitRequest(solution);
       Service3.submitRequest(solution);
       transcope.Complete();
   }
 
Transactional Resources

Transactional programming needs for  working with a resource such as a database or a message queue which is provide capability of participating in a transaction, and able to commit or roll back the changes made during the transaction. Such resources have been around in one form or another for  decades.

Transaction Properties

There are four properties:-
1-The Atomic property
2-The Consistent property
3-The Isolated property
4-The Durable property

1-The Atomic property

 Atomicity means that all the operations must either succeed as a group or fail as a group. If one part of the transaction fails, the entire transaction fails.means that when a transaction completes, all the changes it made to the resource state must be made as if they were all one atomic, indivisible operation.

2-The Consistent property
 
A consistent transaction is one that, when it is complete, leaves the data store in a legal state. Legal state means that no integrity constraints are violated.Note that consistency is different from atomicity. Even if all the changes are committed as one atomic operation, the transaction is required to guarantee that all those changes are consistent that they "make sense and consistent transactions mean that the outcome is exactly what we expected it to be.

3-The Isolated property

Isolated means no other entity  is able to see the intermediate state of the resources during the transaction That is, each transaction is unaware of other transactions executing concurrently in the system  because it may be inconsistent.For a transaction to follow the isolation property, the changes that are part of the transaction should not be available until the transaction is complete.

4-The Durable property

A transaction must survive failure to be called as durable. Once the transaction is committed, any kind of failure that might affect the data store should not affect it.durability is really a range of options. How resilient to such catastrophes the resource should be is an open question that depends on the nature and sensitivity of the data.

Transaction Protocols and Managers

WCF supports the two-phase commit process but the transaction protocol that is used varies based on the situation. WCF supports the following three types of transaction protocols:

1-Lightweight protocol

Lightweight protocol  is used in a local context only, inside the same app domain to manage transactions . Under this protocol, Transaction must be within a single AppDomain. There should not be any cross calls for other AppDomains, so logically no client-service calls are allowed..The lightweight protocol is used only inside a service or outside services.Lightweight protocol  cannot propagate the transaction across the app domain boundary  nor can it flow the transaction across any service boundary .  The Lightweight protocol yields the best performance compared with the other protocols

2-OleTx Protocol

OleTx protocol is used to propagate transactions across app domain, process, and machine boundaries, and to manage the two-phase commit protocol.he OLE Transaction (OleTx) protocol is the standard for use with distributed transactions in a homogeneous environment.The protocol uses RPC calls, and the exact binary format of the calls is Windows-specific. As a result of the use of both the RPC and the Windows-specific format, it cannot go across firewalls or interoperate with non-Windows parties. Under this protocal communication through firewalls is now allowed and cross-platform communications are also not allowed. Because of this, it is typically used in a Windows intranet scenario.This is usually not a problem because the primary use for the OleTx protocol is for managing transactions in an intranet, in a homogenous Windows environment, and when a single transaction manager is involved

3-WSAT Protocol

WS-Atomic (WS-AT) protocol is not different from OleTx in terms of its capabilities.This protocol is similar to the OleTx protocol in that it too can propagate the transaction across app domain, process, and machine boundaries, and manage the two-phase commit protocol.It is a two-phase protocol that can propagate transactions across process, App-Domain, and computer boundaries.the WSAT protocol is based on an industry standard and, when used over HTTP with text encoding, can go across firewalls.The main difference is that although OleTx is limited to computers running Windows behind a firewall, WS-AT is an industry standard that can be used over HTTP

Resources and promotion
 
LTM promotion:-LTM is the Lightweight Transaction Manager.if the transaction tries to enlist a second durable resource or the transaction is propagated to a service, WCF will promote the transaction from the LTM to the DTC

KTM promotion:-The KTM can manage a transaction as long as it interacts with a single KRM and as long as the transaction is local.

Requiring transaction flow

The Client/Service mode requires the use of a transaction-aware binding with transaction flow enabled, and yet this is not enforced by WCF at the service load time

[AttributeUsage(AttributeTargets.Class)]
public class BindingRequirementAttribute : Attribute,IServiceBehavior
{
   public bool TransactionFlowEnabled //Default is false
   {get;set;}
   //More members
}

The BindingRequirementAttribute
[AttributeUsage(AttributeTargets.Class)]
public class BindingRequirementAttribute : Attribute,IServiceBehavior
{
   public bool TFEnabled
   {get;set;}

   void IServiceBehavior.Validate(ServiceDescription description,
                                  ServiceHostBase host)
   {
      if(TFEnabled == false)
      {
         return;
      }
      foreach(ServiceEndpoint endpoint in description.Endpoints)
      {
         Exception exception = new InvalidOperationException(...);

         foreach(OperationDescription operation in endpoint.Contract.Operations)
         {
            foreach(IOperationBehavior behavior in operation.Behaviors)
            {
               if(behavior is TransactionFlowAttribute)
               {
                  TransactionFlowAttribute  TFattribute =
                                              behavior as TransactionFlowTFattribute;
                  if(TFattribute.Transactions == TransactionFlowOption.Allowed)
                  {
                     if(endpoint.Binding is NetTcpBinding)
                     {
                        NetTcpBinding tcpBinding =
                                                 endpoint.Binding as NetTcpBinding;
                        if(tcpBinding.TransactionFlow == false)
                        {
                           throw exception;
                        }
                        break;
                     }
                     ...  //Similar checks for the rest of the transaction-aware
                          //bindings

                     throw new InvalidOperationException(...);
                  }
               }
            }
         }
      }
   }
   void IServiceBehavior.AddBindingParameters(...)
   {}
   void IServiceBehavior.ApplyDispatchBehavior(...)
   {}
} 
Example of Explicit transaction management

WCF services can work directly against a transactional resource and manage the transaction explicitly using programming models such as that offered by ADO.NET
[ServiceContract]
interface IMyContract
{
   [OperationContract]
   void operation( );
}

class MyService : IMyContract
{
   public void operation( )
   {
      //Avoid this programming model:

      string str = "...";
      IDbConnection connection = new SqlConnection(str);
      connection.Open( );
      IDbCommand idbcomm = new SqlCommand( );
      idbcomm.Connection = connection;
      IDbTransaction transaction = connection.BeginTransaction( );//Enlisting
      idbcomm.Transaction = transaction;
      try
      {
         /* Interact with database here, then commit the transaction */
         transaction.Commit( );
      }
      catch
      {
         transaction.Rollback( ); //Abort transaction
      }
      finally
      {
         connection.Close( );
         idbcomm.Dispose( );
         transaction.Dispose( );
      }
   }
}
 
WCF Resource Managers

A WCF Resource Manager (RM) is any resource that supports both automatic enlistment and the two-phase commit protocol managed by one of WCF's transaction managers. The resource must detect that it is being accessed by a transaction and automatically enlist in it exactly once. The RM can be either a durable resource or a volatile resource, such as a transactional integer, string, or collection.

DynamicPopulateExtender Control

DynamicPopulate is a simple extender that replaces the contents of a control with the result of a web service or page method call.The DynamicPopulate control in the ASP.NET AJAX Control Toolkit calls a web service (or page method) and fills the resulting value into a target control on the page, without a page refresh.

DynamicPopulateExtender  property

TargetControlID -It represnt id of the button.
ClearContentsDuringUpdate -It is bydefult true for clear the HTML  contents when new updation starts.
ServicePath-The URL of the web service to call
ServiceMethod -The name of the method to call on the page or web service
UpdatingCssClas- The CSS class to apply to the target during asynchronous calls.
CustomScript -Its used for calling a Web or Page method. 
ContextKey -An arbitrary string value to be passed to the web method
CacheDynamicResults-Whether the results of the dynamic population should be cached and not fetched again after the first load.

How to use DynamicPopulateExtender control
 
Step 1. Start -> All Programs -> Visual Studio 2005 or Visual Studio 2008

Step 2. Now go to File Menu -> New -> Web Site

Step 3. Under Visual Studio Installed Template-> Choose ASP.NET WEB SITE -> Choose
File System from the location combo box -> Set the path by the browse button - > Choose the language from the Language ComboBox (Visual C# ,Visual Basic , J #)

Choose Visual C#

Step 4. Click on the OK Button.


Step 5. Now drag some controls under the AJAX Extensions.
First control you are going to drag and drop on the page is - Script Manager.


After that .


 
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/
xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>


<script runat="server">
  [System.Web.Services.WebMethod]  
    [System.Web.Script.Services.ScriptMethod] 
 public String operation(string s)
  {
    return  Convert.ToString( "You Selected Pizza " + s);
  }
   
</script>
    
</head>
<body>
 <form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
        </asp:ScriptManager>
<script type = "text/javascript"> 
  function UpdatePizza(chkcount)
  {
  var behavior = $find('dp1');
  var value = '';
  for (i = 0; i < chkcount; i++)
  {
    if (document.forms[0].chknumber[i].checked == true)
      value = ' With ' + document.forms[0].chknumber[i].value + ',';
  }
  if (behavior)
  {
    behavior.populate(value);
  }
}
 
Sys.Application.add_load(function(){Updatenumber(3);});
</script>
   
    <br />
<label for="Chk1"><input id="Chk1" type="checkbox"  name="chknumber" 
    value="100" onclick="Updatenumber(3);" />100</label><br />
<label for="Chk2"><input id="Chk2" type="checkbox"  name="chknumber" value="200"  
    onclick="Updatenumber(3);" />200</label><br />
<label for="Chk3"><input id="Chk3" type="checkbox"  name="chknumber" 
    value="300"  onclick="Updatenumber(3);" />300</label><br />
<br />
    
        <asp:Panel ID="Panel1" runat="server">
        </asp:Panel>
        <cc1:DynamicPopulateExtender ID="DynamicPopulateExtender1" runat="server" TargetControlID="Panel1" 
BehaviorID="dp1" ServiceMethod="operation">
        </cc1:DynamicPopulateExtender>
        
    

    </form>
</body> 
</html>
 
Step 6. Now run your web site by Ctrl + F5  Step 7. Output is   

 

1 comment: