Sunday, September 6, 2015

DIFFERENCES

DIFFERENCES

WCF Service Base Address vs endpoint address

baseAddress is just that, the base address for your endpoints (unless specified explicitly). So every <endpoint> will inherit from <baseAddress> (which is why they are usually "" and "mex"). e.g.
<baseAddresses>
  <add baseAddress="http://127.0.0.1:1337/" />
</baseaddresses>
...
<endpoint address="" contract="MyService.IMyContract" ... />
<endpoint address="mex" contract="IMetadataExchange" ... />
You now have two endpoints:
  • http://127.0.0.1:1337/ - service endpoint
  • http://127.0.0.1:1337/mex - metadata endpoint
By exempting the <baseAddress> you're requiring the <endpoints> to both be fully qualified (including the mex (which is not)). e.g.
<baseAddresses></baseaddresses>
...
<endpoint address="net.tcp://127.0.0.1:1337/" contract="MyService.IMyContract" ... />
<endpoint address="http://127.0.0.1:1337/mex" contract="IMetadataExchange" ... />
You now have two different endpoints:
  • net.tcp://127.0.0.1:1337/ - service endpoint
  • http://127.0.0.1:1337/mex - metadata endpoint
In BizTalk for WCF end point, we get both ServiceBehavior and EndPointBehavior as behavior extensions. Then a question comes across to mind is, why two different behaviors when we can use single service or end point one? Found out the answer, thanks to different sources and blogs. I haven't used WCF Services as such, so needed a clear answer for this.
The ApplyDispatchBehavior method on IServiceBehavior has access to all endpoints and their runtime components and so shouldn't that be enough for wiring up customization? The short answer is yes, but there are subtle differences.
 Some usability differences are
1. ServiceBehavior applies only on service while EndpointBehavior applies on both client and service.
2. ServiceBehavior can be specified via config/attribute/code while endpointbehavior can be specified via config/code.
 3. ServiceBehavior has access to all ServiceEndpoints dispatch runtime and so could modify all dispatch runtimes while Endpointbehavior gets called with the runtime for that endpoint only.
Look at it this way, ServiceBehavior lets you access runtime parameters for all endpoints while Endpointbehavior lets you access runtime components only for that endpoint. So if you have a need to extend functionality that spawns the entire contract (or multiple contracts) then use ServiceBehavior and if you are interested in extending one specific endpoint then use Endpointbehavior.
And of course there is the biggest difference, if you want to customize endpoints on client then the only option is IEndpointBehavior.
The Contract specifies what the service actually does. In other words, what Operations are valid.
The Endpoint specifies an actual running instance of the service. It is the actual "service" in the sense that it executes, either as a Windows Service or under IIS.
The Service Behavior defines how the endpoint interacts with clients. Attributes like security, concurrency, caching, logging, etc. - those are all part of the behavior.
There is also an Operation Behavior which is similar to the Service Behavior but only gets applied when a specific operation is run.
Endpoint in WCF service is the combination of three things address, binding and contract. Service endpoint is for the server, server where your WCF service is hosted. Service endpoint defines where the service is hosted, what are the bindings and the contract i.e. methods and interfaces.

While client endpoint is for the client. Client endpoint specifies which service to connect, where it's located etc.


Code of WCF Server end point looks something as shown below.


WCF Client end point code looks something as shown below.This is generated when you add service reference using add service reference.


The difference between the two of them is that an operation contract is a part of a service contract. WCF provides a manner for exposing web services. The contract of a service ([ServiceContract]) is a set of operational actions ([OperationContract]) that can be consumed by a client. The service is something that is shared between the client and the service provider. In WCF, service contracts are seperated into interfaces in order to provide a level of abstraction between the inernal mechanisme with which the service is working and the definition of a service. So the Service Contract is the definition of the whole service. Once the client gets a remote reference of the service (also called aproxy of the service), he can call one of the operation contracts which are encapsulated into it. For Example, if you want a service for remotely managing a set of students into the database, you will create an interface (that will be your service contract) that you will call IStudentManager (you can call it what you like). And this interface has the operations that will define the set of possibilities given to the client of the web service.
[ServiceContract]
public interface IStudentManager
{

    [OperationContract]
    void AddStudent(Student s);

    [OperationContract]
    void DeleteStudent(int studentId);

    [OperationContract]
    void UpdateStudent(int studentId);

    [OperationContract]
    Student GetStudent(int studentId);

    // TODO: You can add other services operations here
}
In this case, the client will request a remote reference of the service, which will be communicated to him over the network. From this reference (of type IStudentManager): the ServiceContract, will be used to trigger actions on the service. These actions in our case are: Add/Update/Delete/Get Students: The OperationContracts.
I think I found the reason for it. In the WSDL the function gets exposed as the following:
<wsdl:message name="IBusinessUnitDAO_GetBusinessUnitProjects_InputMessage">
  <wsdl:part name="parameters" element="tns:GetBusinessUnitProjects" />
</wsdl:message>
<wsdl:message name="IBusinessFunctionDAO_GetBusinessFunctionProjects_InputMessage">
  <wsdl:part name="parameters" element="tns:GetBusinessFunctionProjects" />
</wsdl:message>
Then in the xsd that defines the tns: namespace we have the following:
<xs:element name="GetBusinessUnitProjects">
  <xs:complexType>
    <xs:sequence>
      <xs:element minOccurs="0" name="businessUnitRefID" type="xs:int" />
    </xs:sequence>
  </xs:complexType>
</xs:element>

<xs:element name="GetBusinessFunctionProjects">
  <xs:complexType>
    <xs:sequence>
      <xs:element minOccurs="0" name="businessFunctionRefID" type="xs:int" />
    </xs:sequence>
  </xs:complexType>
</xs:element>
So the reason for the collision even though the the service is exposing two different contracts is because all of the wsdl part elements are in the same namespace. So when you create two function names that are identical you get duplicate elements with the same name which causes the problem. So the solution to the problem is to add a namespace attribute to each service contract. If we take our original service contract and modify it like so.
[ServiceContract(Namespace="Tracking/BusinessFunction")]
public partial interface IBusinessFunctionDAO {

    [OperationContract]
    BusinessFunction GetBusinessFunction(Int32 businessFunctionRefID);

    [OperationContract]
    IEnumerable<Project> GetProjects(Int32 businessFunctionRefID);
}

[ServiceContract(Namespace="Tracking/BusinessUnit")]
public partial interface IBusinessUnitDAO {

    [OperationContract]
    BusinessUnit GetBusinessUnit(Int32 businessUnitRefID);

    [OperationContract]
    IEnumerable<Project> GetProjects(Int32 businessUnitRefID);
}
When we generate the WSDL we get a WSDL for each namespace we create. This namespace has each port identified with all its operations and elements. So inside each of our seperate WSDL's we get the following:
//File: Tracking.BusinessFunction.wsdl
<wsdl:message name="IBusinessFunctionDAO_GetProjects_InputMessage">
  <wsdl:part name="parameters" element="tns:GetProjects" />
</wsdl:message>

//File: Tracking.BusinessUnit.wsdl
<wsdl:message name="IBusinessUnitDAO_GetProjects_InputMessage">
  <wsdl:part name="parameters" element="tns:GetProjects" />
</wsdl:message>
as you can see they both have the same element name, but because they are in different namespaces the elements no longer conflict with each other. If we take a look at the xsd they now have the same elements defined but with different parameters:
//File: Tracking.BusinessFunction.xsd
<xs:element name="GetProjects">
  <xs:complexType>
    <xs:sequence>
      <xs:element minOccurs="0" name="businessFunctionRefID" type="xs:int" />
    </xs:sequence>
  </xs:complexType>
</xs:element>

//File: Tracking.BusinessUnit.xsd
<xs:element name="GetProjects">
  <xs:complexType>
    <xs:sequence>
      <xs:element minOccurs="0" name="businessUnitRefID" type="xs:int" />
    </xs:sequence>
  </xs:complexType>
</xs:element>
So the answer to my original question is to make each service contract live in a separate namespace so you don't have conflicting port elements. This also gives you the flexibility of having your contracts in separate WSDL's which are easier to manage if you are distributing parts of them.
You could try using an alias perhaps:
[OperationContract(Name = "YourMethodNameHere")]
IEnumerable GetProjects(Int32 businessUnitRefID);
They do the same thing, ultimately - but on a different scope.
[ServiceKnownType] defines a class hierarchy for all methods on this service, or a single method on the service (depending on where you put the attribute). So in this case, this type hierarchy will only be valid and applicable for this service or maybe even just a single method in that service contract.
[KnownType] does the same thing - but on the underlying data contracts. Any service that will be using this data contract now also "inherits" all those potential descendant classes - which might or might not be what you want.
So really - it's just a matter of what scope you want to apply a given declaration to - putting it on the data contract makes it sort of a "global" type hiearchy, while using [ServiceKnownType] allows you to define something that's valid only for one service contract or even just one (or several) methods on that service contract.

WCF- Differences between proxy object, service object and normal class object

Your client proxy is a usual .NET class which is inhereted from ServiceModel.ClientBase class. When you create proxy, .NET environment just adds the logic of consuming your service methods so as if they are locals. Proxy contains the dublicates of your service methods and some constructors, where you can define bindings, endpoints and so on. When you call method in proxy - it opens the chanel, creates a message and sends it to the server. That is what proxy does. It does not contais the logic of your methods.
You service class - is also a usual .NET class, marked with some special service attributes. When you start your service, the .NET environment begins to listen for the messages, sent by clients. And when it recives such messages - it unpacks them, creates the instance of your service class (or uses created already) and executes the method. Then the result is send back in return message.
So client proxy does not contains any logic - it is used only to send messages with info of what method it called and what params are used. The service class contains all the logic of your methods.
The first Save method can be called only with Item or SubItem instance, but The second one accepts only SubItem instance.
The purpose of ServiceKnownTypeAttribute is specify the types that should be included for consideration during deserialization. For more information look at the Data Contract Known Types andServiceKnownTypeAttribute Class

WCF and ASP.NET Web API

.NET Framework 4.5
WCF is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments. (ASP.NET Web APIis a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. This topic presents some guidance to help you decide which technology will best meet your needs.

Choosing which technology to use


The following table describes the major features of each technology.
WCF
ASP.NET Web API
Enables building services that support multiple transport protocols (HTTP, TCP, UDP, and custom transports) and allows switching between them.
HTTP only. First-class programming model for HTTP. More suitable for access from various browsers, mobile devices etc enabling wide reach.
Enables building services that support multiple encodings (Text, MTOM, and Binary) of the same message type and allows switching between them.
Enables building Web APIs that support wide variety of media types including XML, JSON etc.
Supports building services with WS-* standards like Reliable Messaging, Transactions, Message Security.
Uses basic protocol and formats such as HTTP, WebSockets, SSL, JQuery, JSON, and XML. There is no support for higher level protocols such as Reliable Messaging or Transactions.
Supports Request-Reply, One Way, and Duplex message exchange patterns.
HTTP is request/response but additional patterns can be supported through SignalRand WebSockets integration.
WCF SOAP services can be described in WSDL allowing automated tools to generate client proxies even for services with complex schemas.
There is a variety of ways to describe a Web API ranging from auto-generated HTML help page describing snippets to structured metadata for OData integrated APIs.
Ships with the .NET framework.
Ships with .NET framework but is open-source and is also available out-of-band as independent download.
Use WCF to create reliable, secure web services that accessible over a variety of transports. Use ASP.NET Web API to create HTTP-based services that are accessible from a wide variety of clients. Use ASP.NET Web API if you are creating and designing new REST-style services. Although WCF provides some support for writing REST-style services, the support for REST in ASP.NET Web API is more complete and all future REST feature improvements will be made in ASP.NET Web API. If you have an existing WCF service and you want to expose additional REST endpoints, use WCF and the WebHttpBinding
ASP.NET Web API is a framework for building web services that are exposed over HTTP. It is very well suited to (but not limited to) building RESTful web services.
Such web services are an alternative to building a SOAP RPC / WS* web services in that they are simpler, more light weight, and there's less coupling between client and server.
A traditional "WCF Service" supports SOAP RPC as opposed to REST, and these services tend to be complex and to have a tight coupling between client and server. Wide interoperability can become difficult to achieve. However, a traditional WCF Service can communicate over a wide variety of protocols - TCP being a particularly useful one for internal services (services in the same DMZ).
(While WCF is mostly associated with SOAP RPC-style services, there are at least three attempts in WCF to support the building of RESTful web services. These attempts have all been superseded by the ASP.NET Web API.)
ASP.NET Web API is a best fit for producing public facing RESTful web services - aka Hypermedia APIs - over HTTP. To do this, having a good understanding of the REST architectural style is important before you start using the ASP.NET Web API. See such books as "REST in Practice", "The RESTful Web Services Cookbook" and "Building Hypermedia APIs with HTML5 and Node"
Things WCF does that you cannot do (with ease) using Web API.
  1. Supports SOAP based XML format.
  2. Supports strongly typed data contracts.
  3. Supports a single point of metadata information exchange using WSDL etc.
  4. Supports varied bindings like TCP, Named Pipes, MSMQ, even UDP etc.
  5. Supports varied hosting options like console apps, WAS, IIS, Windows Services.
  6. Supports one way messaging, duplex, message queues out of the box.
  7. Supports multiple authentication schemes like Windows, Forms, Certificates etc.
Things Web API does that you cannot do (with ease) using WCF.
  1. Supports the full features of HTTP. (Uri based access, Http Requests/Response, Http Caching etc.) To do this in WCF you need to additional work to configure it as REST service etc.
  2. Is Lightweight with minimal configuration.
  3. Supports the Routing, Controller/Action MVC paradigm, Model Binding etc.
Basically Web API is an easy way to do RESTful services over Http without knowing much about Web services.
To do the same in WCF, you need to do additional work in terms of httpBindings, UriTemplates, Verbs etc. And that means, understanding WCF first. And then using WCF to implement a RESTFul service over http, which is what Web Api provides out of the box.
WCF Data Services is a framework on top of WCF that makes it easy to create RESTful services that "talk" Atom/OData based on specified LINQ context (object model, LINQ2SQL or Entity Framework).
so for http ajax requests one would choose the wcf web api? The demoes I saw with data services at mix11 just used an url so when to choose what? –  Rasmus Christensen Apr 28 '11 at 13:48
   
you can use ajax against both kinds of services - WCF DS can also return JSON. There's a specific library for working against OData services that can be found here: datajs.codeplex.com –  larsw Apr 28 '11 at 17:44
   
Maybe we can add this as well: "WCF Data Services runs on top of WCF as described but WCF Web API runs on top of ASP.NET but it can be also self-hosted if configured" –  tugberk Nov 30 '11 at 9:37

The WCF Web API abstractions map to ASP.NET Web API roughly as follows
WCF Web APIASP.NET Web API
ServiceWeb API controller
OperationAction
Service contractNot applicable
EndpointNot applicable
URI templatesASP.NET Routing
Message handlersSame
FormattersSame
Operation handlersFilters, model binders
Web API Controllers
Update you service types to be web API controllers by first deriving from ApiController and renaming your service type so that the type name ends with "Controller".
Routing
You can directly map URI templates to routes by defining a route that matches the URI template path and then specifying the method name as the default value for the action route variable. The approach will result in one route per action, which depending on the number of actions may result in significant performance overhead.
To consolidate the number of routes consider refactoring your service so that there is one web API controller per resource.

there are no sessions in webhttpbinding.
The REST services architecture is stateless see (REST WS) so it makes no sense to have the a rest service with
InstanceContextMode = PerSession.
The performance improvement using PerSession (however concurrency issues may appear) is for SOAP web-services.
Answering your question I believe that is a fortunate series of events (db connection pooling, database cache, etc) that you see a performance improvement.
As InstanceContextMode.PerCall is the stateless mode for WCF it is also instantiation mode of your rest service, even if you specified the PerSession as InstanceContextMode.

No comments:

Post a Comment