Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Tuesday, June 12, 2012

WCF REST Service

WCF REST Service
REST stands for Representational State Transfer and is an architectural style. REST provides an easier way of data access comparing with the SOAP protocol. REST and SOAP relies on HTTP protocol.REST provides an alternative to SOAP and WSDL.
REST uses some common HTTP methods to insert/delete/update/retrieve information which is below:
  1. GET - Requests a specific representation of a resource
  2. PUT - Creates or updates a resource with the supplied representation
  3. DELETE - Deletes the specified resource
  4. POST - Submits data to be processed by the identified resource 

What is JSON?

JSON represents JavaScript Object Notation and is an open standard lightweight data interchange format in human readable form. Shortly, it is a data representation format.
JSON provides a simple alternative to the Fatty XML format of data representation. For example a class with properties name and age can be represented as:
eg:
{"Firstname" : "sudhakar",
  "Lastname" : "Boyina",
  "Address"  :  "Hyderabad"}



Search result 1
Search result 2
Search result 3

Sunday, June 10, 2012

Difference between WCF and Web service

Web Service in ASP.NET

A Web Service is programmable application logic accessible via standard Web protocols. One of these Web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C submitted note (as of May 2000) that uses standards based technologies (XML for data description and HTTP for transport) to encode and transmit application data.
Consumers of a Web Service do not need to know anything about the platform, object model, or programming language used to implement the service; they only need to understand how to send and receive SOAP messages (HTTP and XML).

WCF Service

Windows Communication Foundation (WCF) is a framework for building service-oriented applications. Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that requests data from a service endpoint. The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data.
In what scenarios must WCF be used
  • A secure service to process business transactions.
  • A service that supplies current data to others, such as a traffic report or other monitoring service.
  • A chat service that allows two people to communicate or exchange data in real time.
  • A dashboard application that polls one or more services for data and presents it in a logical presentation.
  • Exposing a workflow implemented using Windows Workflow Foundation as a WCF service.
  • A Silverlight application to poll a service for the latest data feeds.

Features of WCF

  • Service Orientation
  • Interoperability
  • Multiple Message Patterns
  • Service Metadata
  • Data Contracts
  • Security
  • Multiple Transports and Encodings
  • Reliable and Queued Messages
  • Durable Messages
  • Transactions
  • AJAX and REST Support
  • Extensibility 

Difference between Web Service in ASP.NET & WCF Service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.
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

Saturday, June 9, 2012

WCF Indroduction


WINDOWS COMMUNICATION FOUNDATION

Overview
Windows Communication Foundation takes many existing communication technologies, such as Web Services, Windows Remoting, Microsoft Message Queuing, and abstracts them into a single technology.  In most cases, this simplifies the way you communicate with other applications.  It also allows you to communicate with other applications without being coupled to a specific technology.  Therefore, you could use Web Services over SOAP to begin with, and later move to remote procedure calls (RPC) without changing your code, just the configuration of WCF.

The Basics

There are a few basic tasks when creating a WCF service.  The basic tasks that must be performed are, in order:

  1. Define the service contract. A service contract specifies the signature of a service, the data it exchanges, and other contractually required data.
  2. Implement the contract. To implement a service contract, create the class that implements the contract and specify some custom behaviors that the runtime should have.
  3. Configure the service by specifying endpoint information and other behavior information.
  4. Host the service in an application.
  5. Build a client application.

Example

To display a step-by-step enactment of the above steps, let’s define a web service that reports the current date/time:

1.1 Define a Service Contract

First, let’s create a project to house our service contract.  Let’s call it WCFDateTime.Service.

1.2 Define a Service Contract

Then, let’s define an interface that represents the service we’re going to provide.  In this case, let’s call it IDateTimeService.
public interface IDateTimeService
{
}

 

1.3 Define a Service Contract

          We need to add a method to our service that will return the current date/time:  
public interface IDateTimeService
{
DateTime GetCurrentDateTime();   
}   

 

1.4 Define a Service Contract

Now, we need to decorate our code with attributes so that WCF will recognize our interface and its methods.  Namely, we will add the following attributes:
·         ServiceContractAttribute
o   Identifies an interface as a WCF service contract
·         OperationContractAttribute
o   Identifies methods of an interface as WCF service operations, that is, methods that can be called through WCF
using System.ServiceModel;

[ServiceContract]
public interface IDateTimeService
{
     [OperationContract]
DateTime GetCurrentDateTime();   
}

In order to use the above attributes, you’ll need to add a reference to the System.ServiceModel assembly.  The service contract is now ready to be used.

 

2.1 Implement the Contract

Now that we’ve defined our service contract, we can move on to implementing it.  First, let’s create another project to house our server application.  Let’s call it WCFDateTime.Server, and make it a Console Application project.

2.2 Implement the Contract

Now, let’s implement the IDateTimeService.  The implementation is going to run on our server, to provide the date/time to whoever is going to consume our service.
In the WCFDateTime.Server project, let’s create a class called DateTimeService and have it implement IDateTimeService:
using WCFDateTime.Service;

public class DateTimeService : IDateTimeService
{
}
         
Remember to add a reference to the WCFDateTime.Service project so you can use IDateTimeService.

2.3 Implement the Contract

The above code will obviously not compile, because we did not implement the GetCurrentDateTime method:
public class DateTimeService : IDateTimeService
{
     public DateTime GetCurrentDateTime()
     {
          return DateTime.Now;
     }   
}
          That’s it!  The DateTimeService is now ready to be used.

3.1 Configure the Service

Now we need to configure our service so it can be consumed by client applications.  The simplest way to accomplish this is by adding an application configuration file (app.config or web.config) to the WCFDateTime.Server project:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.serviceModel>
        <services>
            <service name="WCFDateTime.Server.DateTimeService">               
                <endpoint
                    address="http://localhost:8081/DateTimeService"
                    binding="wsHttpBinding"
                    contract="WCFDateTime.Service.IDateTimeService" />               
            </service>
        </services>
    </system.serviceModel>
</configuration>
          When defining an endpoint for WCF, remember your A-B-Cs:
1.   Address (where)
2.   Binding (how)
3.   Contract (what)

The address specifies the address where you want the service to be located.
The binding specifies the transport you want to use in order to provide the service.
The contract specifies what service will be provided

4.1 Host the Service in an Application

Now that WCF has been configured, the simplest way to host this service is to create a Console Application and use the ServiceHost class.  First, add a reference to the System.ServiceModel assembly.  Then, In the program.cs file of WCFDateTime.Server, do the following:

using System.ServiceModel;

namespace WCFDateTime.Server
{
    class Program
    {
        static public void Main(string[] args)
        {
            // Get a host for our service
            ServiceHost serviceHost = new ServiceHost(
                typeof(DateTimeService)
            );
   
            // Open the service host to start listening for incoming requests
            serviceHost.Open();

            // The service can now be accessed
      Console.WriteLine("The service is ready.");
      Console.WriteLine("Press <ENTER> to terminate service.");
      Console.ReadLine();

            // Close the service host
            serviceHost.Close();
        }
    }
}

By simply running this application, we expose our service so that client applications can use it.

5.1 Build a Client Application

To build a client application, we must create a new project for it.  Let’s call it WCFDateTime.Client, and make it a Console Application as well.

 

5.2 Build a Client Application

Now, we need to add an Application Configuration file, and give it some settings that will allow us to connect to the service we just created:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <system.serviceModel>       
        <client>
            <endpoint
                address="http://localhost:8081/DateTimeService"
                binding="wsHttpBinding"               
                contract="WCFDateTime.Service.IDateTimeService"
                name="MyDateTimeService">
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>
         
Now that our we’ve configured our WCF client, we can connect to it.  There are two ways to connect to the WCF service we previously created:
1.   Client proxy generation
2.   Channel factories
Most Microsoft articles will point you in the direction of using client proxies; however, for our purposes, channel factories are quicker to implement and more robust in a Model/View/Presenter architecture.


5.3 Build a Client Application

Now, add a reference to the System.ServiceModel and WCFDateTime.Service assemblies, and then add the following to the program.cs file:
using System.ServiceModel;
using WCFDateTime.Service;

class Program
{
    public static void Main(string[] args)
    {
        // Get a channel factory for our service,
        // using the configuration for "MyDateTimeService"
        // in the application configuration file.
        ChannelFactory<IDateTimeService> channelFactory =
            new ChannelFactory<IDateTimeService>("MyDateTimeService");

        // Get an instance of our service
        IDateTimeService service = channelFactory.CreateChannel();
       
        // Get the server’s date/time
        DateTime dt = service.GetCurrentDateTime();

        // Write the current server date/time
        Console.WriteLine("The current server time is " + dt);

        // Close the connection to our service
        channelFactory.Close();
    }
}

5.4 Build a Client Application

Your client application is now ready to run!  Simply start the WCFDateTime.Server application, and once it’s running, run the WCFDateTime.Client application to see it work!

WCF Interview Questions and Answer

WCF Interview Questions and Answers

Q1. What is WCF?
WCF stands for Windows Communication Foundation. It is a Software development kit for developing services on Windows. WCF is introduced in .NET 3.0. in the System.ServiceModel namespace. WCF is based on basic concepts of Service oriented architecture (SOA)

Q2. What is endpoint in WCF service?
The endpoint is an Interface which defines how a client will communicate with the service. It consists of three main points: Address,Binding and Contract.

Q3. Explain Address,Binding and contract for a WCF Service?
Address:Address defines where the service resides.
Binding:Binding defines how to communicate with the service.
Contract:Contract defines what is done by the service.

Q4. What are the various address format in WCF?
a)HTTP Address Format:--> http://localhost:
b)TCP Address Format:--> net.tcp://localhost:
c)MSMQ Address Format:--> net.msmq://localhost:

Q5. What are the types of binding available in WCF?
A binding is identified by the transport it supports and the encoding it uses. Transport may be HTTP,TCP etc and encoding may be text,binary etc. The popular types of binding may be as below:
a)BasicHttpBinding
b)NetTcpBinding
c)WSHttpBinding
d)NetMsmqBinding

Q6. What are the types of contract available in WCF?
The main contracts are:
a)Service Contract:Describes what operations the client can perform.
b)Operation Contract : defines the method inside Interface of Service.
c)Data Contract:Defines what data types are passed
d)Message Contract:Defines wheather a service can interact directly with messages

Q7. What are the various ways of hosting a WCF Service?
a)IIS b)Self Hosting c)WAS (Windows Activation Service)

Q8. WWhat is the proxy for WCF Service?
A proxy is a class by which a service client can Interact with the service.
By the use of proxy in the client application we are able to call the different methods exposed by the service


Q9. How can we create Proxy for the WCF Service?
We can create proxy using the tool svcutil.exe after creating the service.
We can use the following command at command line.
svcutil.exe *.wsdl *.xsd /language:C# /out:SampleProxy.cs /config:app.config

Q10.What is the difference between WCF Service and Web Service?
a)WCF Service supports both http and tcp protocol while webservice supports only http protocol.
b)WCF Service is more flexible than web service.

Q11.What is DataContract and ServiceContract?Explain
Data represented by creating DataContract which expose the
data which will be transefered /consumend from the serive
to its clients.

Q12.What is .NET 3.0?

In one simple equation .NET 3.0 = .NET 2.0 + Windows Communication Foundation + Windows
Presentation Foundation + Windows Workflow Foundation + Windows Card Space.

Q13.What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.
First let us give a short answer to this: - “WCF (Indigo was the code name for WCF) is a
unification of .NET framework communication technologies
“.WCF is a unification technology,

Q14.which unites the following technologies:-
• NET remoting
• MSMQ
• Web services
• COM+.

Q15.What was the code name for WCF?
The code name of WCF was Indigo .
WCF is a unification of .NET framework communication technologies which unites the following technologies:-

1.Web services
2.MSMQ
3.NET remoting
4.COM+

Q16.What are the main components of WCF?
The main components of WCF are
1. Service class
2. Hosting environment
3. End point

Q17.Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.
They are
1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)

Q18.What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.

Q19.What are different elements of WCF Srevices Client configuration file?
WCF Services client configuration file contains endpoint, address, binding and contract.
A sample client config file looks like

Q20.What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

Q21.What are ends, contract, address, and bindings?
The above terminologies are the core on which SOA stands. Every service must expose one or more ends by which the service can be available to the client. End consists of three important things where, what and how:-
• Contract (What)
Contract is an agreement between two or more parties. It defines the protocol how client should communicate with your service. Technically, it describes parameters and return values for a method.
• Address (Where)
An Address indicates where we can find this service. Address is a URL, which points to the
location of the service.
• Binding (How)
Bindings determine how this end can be accessed. It determines how communications is done.
For instance, you expose your service, which can be accessed using SOAP over HTTP or
BINARY over TCP. So for each of these communications medium two bindings will be created.
Below figure, show the three main components of end. You can see the stock ticker
is the service
class, which has an end hosted on http://www.soa.com with HTTP and TCP binding support and using
Stock Ticker interface type.

Q22.What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

Q23.WCF supports nine types of bindings?

Basic binding
Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

This binding is used when we need to use SOAP over HTTP. This binding
can also be configured to be used as HTTPS. It can be also configured to send data in plain text or in optimized form like MTOM.

TCP binding
Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.
This binding sends binary-encoded SOAP, including support for reliable
message transfer, security, and transactions, directly over TCP. The biggest disadvantage of
NetTcpBinding is that both server and client should be also made in .NET language.

Peer network binding
Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.

IPC binding
Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.

Web Service (WS) binding
Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

It is same like BasicHttpBinding. In short, it uses SOAP over HTTP. But with
it also supports reliable message transfer, security and transaction. WS-Reliable Messaging,
security with WS-Security, and transactions with WS-Atomic Transaction supports reliable
message.

Federated WS binding
Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

Duplex WS binding
Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

MSMQ binding
Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

MSMQ integration binding
Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

This binding sends binary-encoded SOAP over MSMQ. This binding can
only be used for WCF-to-WCF communication.

Q24.What are the different concurreny modes available in WCF?
1. Single
2. Reentrant
3. Multiple

Q25.Are WCF services protected from concurrent access by default?
Yes, WCF services are protected from concurrent access by default, as the concurrency mode of a WCF service is set to Single by default.

Q26.Explain Single Concurrency Mode?
In a Single concurrency mode only one request is processed by the same service instance. A lock is acquired while a request is processed by a service instance. Other threads, if any, are queued, until they timeout. Once the lock is released when the current request completes, next thread in the queue can then access the objects.

Q27.What effect does Single concurreny mode setting have on PerCall, PerSession and Singleton services?
PerCall services and Single Concurreny mode : A new service instance is allocated for each thread. Here, concurrency is not an issue and Single mode setting has no impact on the throughput and concurrent calls can be processed.

Q28.PerSession services and Single Concurreny mode : Service instances are protected against multithreaded clients. Single mode impacts throughput of single client but multiple clients can get through and concurrent calls can be processed.

Q29.Singleton services and Single Concurreny mode : Service instances are protected against any concurrent calls. Single concurrency mode impacts throughput of singleton. Multiple threads and clients cannot get through and no concurrent calls can be processed.

Q30.Explain Reentrant Concurrency Mode?
Reentrant concurrency mode is useful when services issue callbacks to clients, If callback operations are not one-way. Services release the acquired lock upon exit to make the callback and another thread is able to acquire the lock. In this case, return from callback will queue.

Q31.What effect does Reentrant concurreny mode setting have on PerCall, PerSession and Singleton services?
PerCall services and Reentrant Concurreny mode : In a case where PerCall services may need reentrancy, if we set the concurrency mode to Single, deadlock is guaranteed, where as if it is In Reentrant mode, we will have no problem.

Q32.PerSession services and Reentrant Concurreny mode : PerSession services allow a multithreaded client to access the service instance

Q33.Singleton services and Reentrant Concurreny mode : Singleton services allow any threads to access the service instance

Q34.What is the effect of Multiple concurrency mode on PerSession services with multithreaded clients?
PerSession services with multithreaded clients can have increased throughput, with Multiple concurrency mode, as no locks are acquired when requests are being processed by a service instance. However, care should be taken to protect shared resources.

Q35.What are different .NET multithreading techniques available to protect a shared resource?
1. Monitor
2. Mutex
3. Semaphore
4. ReadWriterLock
5. Interlocked

Q36.What are the factors that can influence overall throughput for a service, when multiple concurrency mode is enabled?
1. Instancing mode
2. Concurrency mode
3. Throttling behavior

Q37.What is ServiceThrottleBehavior?
ServiceThrottleBehavior provides several settings for throughput control, as shown below.
MaxConcurrentCalls: Maximum concurrent requests allowed. The default is 16 .
MaxConcurrentInstances: Maximum concurrent service instances allowed . The default is int.MaxValue.
MaxConcurrentSessions: Maximum concurrent active sessions. This includes transport, reliable, secure, and application sessions. The default is 10.