Hi Friends,
As we are going through the WCF, we saw in our previous posts how to create and implement a Web service in a WCF.But then again question arises how to access that Web Service??
To access any Web Service we need to create a client for accessing the service.A client in a simple word a person who is going to use the web service, in technical words its a authorized centre or endpoint from which services can be accessed.
We can implement a WCF client in two ways
** Using Completely in code
** Using Configuration Files
Today we will see Entirely in Code
* Implementing a Client for a WCF Service Entirely in Code
* As we know ABC'S are very important for exposing the WCF Services on the network.
* The endpoint address is simple—it’s a network address to which messages are sent.
* In following example we will see how to create a simple WCF client using following steps.
Step I
First, the client defines the interface it wants to call. This interface definition is shared between the client and service. Syntactically, the C# definition is very different from XML or WSDL, but semantically it’s the same. That is, it precisely describes how to access the service capabilities, including the name of the operation and its parameters.
Step II
Then the client creates a ChannelFactory class to create a channel, passing in the ABCs. In this case, the address is an address hosted by an IIS server, the binding is basicHttpBinding, and the contract is the IStockService interface. Finally, the client creates the channel to establish communication with the service and “calls a method” on the service.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.ServiceModel.Description;
namespace MyFirstWCFService
{
public class Program
{
[ServiceContract]
public interface IStockService
{
[OperationContract]
double GetPrice(string ticker);
}
public class StockService : IStockService
{
public double GetPrice(string ticker)
{ return 9.99; }
}
static void Main()
{
ChannelFactory channelFactory =
new ChannelFactory(new BasicHttpBinding(),
new EndpointAddress("http://localhost:8000//MyFirstWCFService"));
IStockService createClient = channelFactory.CreateChannel();
double value = createClient.GetPrice("9.25");
Console.WriteLine("Value is :-{0}", value);
}
}
}
Hope this will help you in creating a client in code.
In next blog we will see how to implement or create a client in configuration files.
Thank You.