Does client consuming WCF service require Interface definition? - wcf

I have been going through the book "Learning WCF" trying to get my head around creating and using WCF web services. The first part of the book walks the reader through creating and then consuming a simple "Hello World" web service.
The problem I am having is that the client application seems to have no know the structure of the WCF Interface when calling it. How can this be necessary if a web service could be called from any number of programming languages?
I have listed the relevant example code below ...
Here is the code for the Interface
[ServiceContract(Namespace="http: //www.thatindigogirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo();
}
Here is the code for the Service that hosts the web service
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost(typeof(HelloIndigo.HelloIndigoService) ,
new Uri("http: //localhost: 8000/HelloIndigo")))
{
host. AddServiceEndpoint(typeof(HelloIndigo. IHelloIndigoService) ,
new BasicHttpBinding(), "HelloIndigoService");
host. Open( );
Console. WriteLine("Press <ENTER> to terminate the service host") ;
Console. ReadLine();
}
}
Here is the code for the client app that consumes the WCF service
This is where I get confused. Since this client application could be any language capable of calling a web service why is there a necessity of knowing the definition of the interface?
using System. ServiceModel;
[ServiceContract(Namespace = "http: //www.thatindigogirl.com/samples/2006/06")]
public interface IHelloIndigoService
{
[OperationContract]
string HelloIndigo( );
}
static void Main(string[ ] args)
{
EndpointAddress ep = new
EndpointAddress("http: //localhost: 8000/HelloIndigo/HelloIndigoService") ;
IHelloIndigoService proxy = ChannelFactory<IHelloIndigoService>.
CreateChannel(new BasicHttpBinding(), ep);
string s = proxy. HelloIndigo();
Console. WriteLine(s) ;
Console. WriteLine("Press <ENTER> to terminate Client.") ;
Console. ReadLine();
}
Am I missing an important point here? Perhaps my understanding of what is needed to consume a web is lacking. My goal is to be able to use WCF to create a .NET service that could be called from any programming language or environment.
Might anyone suggest a good tutorial on creating "cross platform consumable" web services from within .NET? Thanks!

This approach is based on shared interface (the book acutally does not share the interface but instead it uses local copy) and is successfully applied in environment where both client and server are written in .NET. This approach is not usable for interoperability or SOA solutions.
Other approach uses metadata exposed by the service. Metadata are defined as WSDL document plus several XSD documents. These metadata files are way to provide information about your service to both .NET and non .NET developers. The book contains definition of Metadata (mex) endpoint so you will definitely read about that.
Using metadata in .NET means creating service proxy. You can do it automatically using Visual studio's Add service reference or command line utility svcutil.exe. Anyway generated proxy code will probably still contain the interface created from metadata. It is used to create transparent abstraction of the service for the client.

'The interface' doesn't mean a .NET interface file, it means the more general programming interface - a set of objects with properties, and methods with parameters. This is also called the service contract.
The reason that the client and the service need to share (i.e. both know about) the interface is simple when you think about it - if the client doesn't know the interface, how do they know what operations are available and what the expected request/response objects should look like?

Every WCF service is composed of
A - address
B - binding
C - contract
The contract is declared using an interface on the serverside. It declares which methods are available to the client. If you are using a http binding you can invoke a service operation by issuing a http request (using a http client in any library or language - or even a web browser) pointed at the correct address. So the client does not need any interface reference at all. It just needs to follow the ABC of the service.
Here is a nice blog on WCF and Java interopability.

To answer your question on how to develop 'cross platform consumable' web services, consider the REST approach. Making REST-style web services truly makes them independent of the platform that consumes them. Simply put, they use the already well established HTTP protocols everything supports: GET and POST Http methods.
You could then have a Java app simply make POST calls to your WCF services with your own custom XML content in the payload without having to fiddle with more complex stuff like making SOAP wrappers and the like. Check out Rob Bagby's article on REST:
http://www.robbagby.com/rest/rest-in-wcf-part-i-rest-overview/

Related

Can I communicate to a WCF (svcutil) web service using just GET or POST?

I have been given access to a WCF/WSDL web service. I first do this:
svcutil.exe https://<thedomain>/foo/foo.svc?wsdl
to generate the C# class I need. I then plug this class into my C# application and it works fine. Note that I did not develop this server and cannot change it.
Question is this:
How can I communicate with this server without svcutil? I prefer to use just REST (GET and POST).
This way I would be able to connect to it from a Linux or Mac machine, not just Windows.
Update In my C# code, this is what happens:
WSHttpBinding binding = new WSHttpBinding();
EndpointAddress endpoint = new EndpointAddress("<address>");
fooClient client = new fooClient(binding, endpoint);
//(fooClient class came from svcutil)
//I now work with fooClient, call methods on it, etc.
That depends on the bindings in use by the service.
The "default" (read: most commonly used) bindings (basicHttp and wsHttp) implement SOAP 1.1 and SOAP 1.2 respectively, which means you're talking HTTP to the service, but using a specially crafted XML envelope in which your payload must be wrapped.
When the webHttpBinding is applied, you can talk "plain old XML" or JSON to the service, how to do so depends on the applied UriTemplate.
Note that there's no standardized metadata exchange for REST services (at least not as far as WCF is concerned), so even if the service is exposed using a REST binding, the information about how to construct the calls will not be exposed automatically but must instead be documented by the owners explicitly.
REST is an architectural approach. WCF service should be built for REST, not that you just can use it like this. In WCF service "by default" all requests are POSTs.

what is WCF and how does it work?

what is this WCF ? i used web services little bit but don't know about theses WCF, read a lot on google but couldn't get its technical terms like
http://www.codeproject.com/Articles/139787/What-s-the-Difference-between-WCF-and-Web-Services
or msdn.
It says like communication over HTTP and SOAP , serialization, soap etc but yet I'm not qualified to understand these. Help me, guide me and please in easy wordings.
[WebService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Test(string strMsg)
{
return strMsg;
}
}
etc
and how to use them with asp.net ?
Windows communication foundation or Wcf is a framework for building services. Wcf supports exposing web services, services based on urls (rest) or services ment only to work on a single machine, such as two different programs communicating via shared memory.
Basically wcf abstracts the service (a .net interface) and the transport (or in wcf terms, a binding). A single service in Wcf can be exposed as a web service or using shared memory without any actual code changes, the endpoints are all based on app config files.
Perhaps this article on msdn will make things clearer
http://msdn.microsoft.com/en-us/library/ms731082.aspx
Some terms,
Interoperability - to operate, or work together, with something else (inter- between, operate- work together) a wcf service can interoperate with a client written in java for example
Serialization - to convert an object to a stream of bytes that can be sent somewhere and then deserialized back into an object

Add service reference dynamically

Can we add a service reference dynamically to a project without using add reference in visual studio. Does Wsdl Import of metadata will help in achieving this goal can some one help me in dynamically loading and attaching the service to project and use the client in wcf or suggest me a methodology in achieving this.
The .NET framework has a namespace dedicated to this called System.ServiceModel.Discovery. From a high level you use a DiscoveryClient which can locate services available for use.
To be able to locate services with the DiscoveryClient the service info needs to be sent out through the AnnouncementClient class. This class allows a service to publish announcement messages. From the documentation:
An announcement message contains information about the service such as its fully-qualified contract name, any scopes that the service is operating in as well as any custom metadata the service wants to send.
These classes should be everything you need to provide the plumbing for dynamic service discovery and usage.
If you are trying to consume existing third party endpoints (services that are not under your control) there are at least two methods provided in the .NET framework.
MetadataExchangeClient
MetadataResolver
MetadataExchangeClient will connect to a MEX/wsdl endpoint and return back a collection of objects representing the service metadata.
MetadataResolver will return the configuration for a known service if you pass it the MEX/wsdl endpoint and the type to resolve. This allows you import the connection settings without having to specifiy it up front.
To see what else is available explore the System.ServiceModel.Description namespace. It has the two classes above plus others related to dynamic service resolution.
EDIT: This was able to retrieve Metadata for me:
MetadataExchangeClient client = new MetadataExchangeClient(
new Uri("http://localhost:22948/Service1.svc?wsdl"),
MetadataExchangeClientMode.HttpGet);
var response = client.GetMetadata();

Design Question - Handling .NET App Config at a DLL level

I have an existing .NET 3.5 based framework that is extended using custom plugins. In summary plugins implement a common interface and the core framework invokes these via reflection. The framework works perfectly and all is good, however...
I now have a requirement that requires a plugin that communicates with the WCF service. At face value this is simple, add a service reference to the plugin, call the client proxy code and off we go. However...
Due to the way that .NET configuration works the WCF service client configuration should reside within the app.config of the executing application. In this case this is my plugin invoker application. The problem with this is that it breaks the plugin "model" as the generic invoker application now has to have plugin specific configuration within it.
So the question is does anybody know of an alternative mechanism for handling the WCF service client configuration without putting it into the core invoker application configuration?
Having done a little hunting around there are mechanisms to allow a DLL to use its own config file. The issue here is that I don't have access to the underlining code of the service proxy creation and therefore seemingly can't redirect the config reads.
A WCF client's endpoint can be configured programmatically as well.
Here's an example that shows how to invoke a WCF service without the need for a configuration file:
var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
var client = new MyServiceClient(myBinding, myEndpoint);
try
{
client.MyServiceOperation();
client.Close();
}
catch
{
if (client != null)
{
client.Abort();
}
}
Related resources:
ClientBase<TChannel> Constructor (Binding, EndpointAddress)
Answering my own question:
I seem to have found a solution to the problem here:
http://weblogs.asp.net/cibrax/archive/2007/10/19/loading-the-wcf-configuration-from-different-files-on-the-client-side.aspx
In summary this allows you to specify a custom configuration file that contains the WCF configuration as it is generated by Visual Studio - this means that the config can be maintained easily.
Having run a couple of quick tests it seems that it works as it should (with a few tweaks here and there (see the comments on the page).

Web Service vs WCF Service

What is the difference between them?
When would I opt for one over the other?
This answer is based on an article that no longer exists:
Summary of article:
"Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.
You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?
Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out."
... later ...
"should use WCF when we need to communicate with other communication technologies (e,.g. Peer to Peer, Named Pipes) rather than Web Service"
From What's the Difference between WCF and Web Services?
WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot more than what is traditionally considered as "web services".
WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. Common scenarios for hosting WCF services are IIS,WAS, Self-hosting, Managed Windows Service.
The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in performance as compared to XmlSerializer.
Web Service
is based on SOAP and return data in XML form.
It support only HTTP protocol.
It is not open source but can be consumed by any client that understands xml.
It can be hosted only on IIS.
WCF
is also based on SOAP and return data in XML form.
It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
The main issue with WCF is, its tedious and extensive configuration.
It is not open source but can be consumed by any client that understands xml.
It can be hosted with in the applicaion or on IIS or using window service.
Basic and primary difference is, ASP.NET web service is designed to exchange SOAP messages over HTTP only while WCF Service can exchange message using any format (SOAP is default) over any transport protocol i.e. HTTP, TCP, MSMQ or NamedPipes etc.
What is the difference between web service and WCF?
Web service use only HTTP protocol while transferring data from one application to other application.
But WCF supports more protocols for transporting messages than ASP.NET Web services. WCF supports sending messages by using HTTP, as well as the Transmission Control Protocol (TCP), named pipes, and Microsoft Message Queuing (MSMQ).
To develop a service in Web Service, we will write the following code
[WebService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Test(string strMsg)
{
return strMsg;
}
}
To develop a service in WCF, we will write the following code
[ServiceContract]
public interface ITest
{
[OperationContract]
string ShowMessage(string strMsg);
}
public class Service : ITest
{
public string ShowMessage(string strMsg)
{
return strMsg;
}
}
Web Service is not architecturally more robust. But WCF is architecturally
more robust and promotes best practices.
Web Services use XmlSerializer but WCF uses DataContractSerializer. Which is
better in performance as compared to XmlSerializer?
For internal (behind firewall) service-to-service calls we use the net:tcp
binding, which is much faster than SOAP.
WCF is 25%—50% faster than ASP.NET Web Services, and approximately 25%
faster than .NET Remoting.
When would I opt for one over the other?
WCF is used to communicate between other applications which has been developed on other platforms and using other Technology.
For example, if I have to transfer data from .net platform to other application which is running on other OS (like Unix or Linux) and they are using other transfer protocol (like WAS, or TCP) Then it is only possible to transfer data using WCF.
Here is no restriction of platform, transfer protocol of application while transferring the data between one application to other application.
Security is very high as compare to web service
The major difference is time-out, WCF Service has timed-out when there is no response, but web-service does not have this property.