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

Friday, 15 April 2016

Understanding different types of WCF Contracts

WCF contract specify the service and its operations. WCF has five types of contracts: service contract, operation contract, data contract, message contract and fault contract.




  1. Service Contract


    A service contract defines the operations which are exposed by the service to the outside world. A service contract is the interface of the WCF service and it tells the outside world what the service can do. It may have service-level settings, such as the name of the service and namespace for the service.

    1. [ServiceContract]

    2. interface IMyContract

    3. {

    4. [OperationContract]

    5. string MyMethod();

    6. }

    7.  

    8. class MyService : IMyContract

    9. {

    10. public string MyMethod()

    11. {

    12. return "Hello World";

    13. }

    14. }


  2. Operation Contract


    An operation contract is defined within a service contract. It defines the parameters and return type of an operation. An operation contract can also defines operation-level settings, like as the transaction flow of the op-eration, the directions of the operation (one-way, two-way, or both ways), and fault contract of the operation.

    1. [ServiceContract]

    2. interface IMyContract

    3. {

    4. [FaultContract(typeof(MyFaultContract))]

    5. [OperationContract]

    6. string MyMethod();

    7. }


  3. Data Contract


    A data contract defines the data type of the information that will be exchange be-tween the client and the service. A data contract can be used by an operation contract as a parameter or return type, or it can be used by a message contract to define elements.

    1. [DataContract]

    2. class Person

    3. {

    4. [DataMember]

    5. public string ID;

    6. [DataMember]

    7. public string Name;

    8. }


    9. [ServiceContract]

    10. interface IMyContract

    11. {

    12. [OperationContract]

    13. Person GetPerson(int ID);

    14. }


  4. Message Contract


    When an operation contract required to pass a message as a parameter or return value as a message, the type of this message will be defined as message contract. A message contract defines the elements of the message (like as Message Header, Message Body), as well as the message-related settings, such as the level of message security.

    Message contracts give you complete control over the content of the SOAP header, as well as the structure of the SOAP body.

    1. [ServiceContract]

    2. public interface IRentalService

    3. {

    4. [OperationContract]

    5. double CalPrice(PriceCalculate request);

    6. }

    7.  

    8. [MessageContract]

    9. public class PriceCalculate

    10. {

    11. [MessageHeader]

    12. public MyHeader SoapHeader { get; set; }

    13. [MessageBodyMember]

    14. public PriceCal PriceCalculation { get; set; }

    15. }

    16.  

    17. [DataContract]

    18. public class MyHeader

    19. {

    20. [DataMember]

    21. public string UserID { get; set; }

    22. }

    23.  

    24. [DataContract]

    25. public class PriceCal

    26. {

    27. [DataMember]

    28. public DateTime PickupDateTime { get; set; }

    29. [DataMember]

    30. public DateTime ReturnDateTime { get; set; }

    31. [DataMember]

    32. public string PickupLocation { get; set; }

    33. [DataMember]

    34. public string ReturnLocation { get; set; }

    35. }



  5. Fault Contract


    A fault contract defines errors raised by the service, and how the service handles and propagates errors to its clients. An operation contract can have zero or more fault contracts associated with it.

    1. [ServiceContract]

    2. interface IMyContract

    3. {

    4. [FaultContract(typeof(MyFaultContract1))]

    5. [FaultContract(typeof(MyFaultContract2))]

    6. [OperationContract]

    7. string MyMethod();


    8. [OperationContract]

    9. string MyShow();

    10. }

What do you think?

I hope you will enjoy the tips while programming with WCF. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Monday, 11 April 2016

Difference between WCF and Web API and WCF REST and Web Service

The .Net framework has a number of technologies that allow you to create HTTP services such as Web Service, WCF and now Web API. There are a lot of articles over the internet which may describe to whom you should use. Now a days, you have a lot of choices to build HTTP services on .NET framework. In this article, I would like to share my opinion with you over Web Service, WCF and now Web API.


Web Service



  1. It is based on SOAP and return data in XML form.

  2. It support only HTTP protocol.

  3. It is not open source but can be consumed by any client that understands xml.

  4. It can be hosted only on IIS.

WCF



  1. It is also based on SOAP and return data in XML form.

  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.

  3. The main issue with WCF is, its tedious and extensive configuration.

  4. It is not open source but can be consumed by any client that understands xml.

  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest



  1. To use WCF as WCF Rest service you have to enable webHttpBindings.

  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.

  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files

  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified

  5. It support XML, JSON and ATOM data format.

Web API



  1. This is the new framework for building HTTP services with easy and simple way.

  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.

  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)

  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.

  5. It can be hosted with in the application or on IIS.

  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.

  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API



  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.

  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.

  3. Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).

  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

What do you think?

I hope, you have got when to use WCF, Web API and Web Service. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Tuesday, 5 April 2016

Difference between WCF and Web API and WCF REST and Web Service

e .Net framework has a number of technologies that allow you to create HTTP services such as Web Service, WCF and now Web API. There are a lot of articles over the internet which may describe to whom you should use. Now a days, you have a lot of choices to build HTTP services on .NET framework. In this article, I would like to share my opinion with you over Web Service, WCF and now Web API.


Web Service



  1. It is based on SOAP and return data in XML form.

  2. It support only HTTP protocol.

  3. It is not open source but can be consumed by any client that understands xml.

  4. It can be hosted only on IIS.

WCF



  1. It is also based on SOAP and return data in XML form.

  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.

  3. The main issue with WCF is, its tedious and extensive configuration.

  4. It is not open source but can be consumed by any client that understands xml.

  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest



  1. To use WCF as WCF Rest service you have to enable webHttpBindings.

  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.

  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files

  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified

  5. It support XML, JSON and ATOM data format.

Web API



  1. This is the new framework for building HTTP services with easy and simple way.

  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.

  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)

  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.

  5. It can be hosted with in the application or on IIS.

  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.

  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API



  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.

  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.

  3. Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).

  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

I hope, you have got when to use WCF, Web API and Web Service. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Friday, 1 April 2016

Differences between WCF and Web service

What is Web Service?

Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by using standard web protocols and data formats, such as HTTP, XML and SOAP. 

What is WCF (windows communication foundation) Service?

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

Web Service vs. WCF Service

1. Web service is there with .net framework from version 1.0. Whereas, WCF service got introduced with .NET 3.0.
2. ASP.NET Web services send and receive messages by using SOAP over HTTP or HTTPS.
WCF services use SOAP by default, but the messages can be in any format, and conveyed by using any transport protocol like HTTP,HTTPs, WS- HTTP, TCP, Named Pipes, MSMQ, P2P(Point to Point) etc.

3. Web services have “.asmx” extension, whereas Wcf services have “.svc” extension.
4. The asmx page uses “WebService” directive where as the svc page uses “ServiceHost” directive.
5. ASP.NET Web services rely on the XmlSerializer in System.XML.Serialization namespace for serialization (to translate data in .NET Framework types to XML and vice versa for transmission to or from a service). XmlSerializer has some limitations like:

  • Only public properties/fields can be serialized.

  • Only collection classes implementing IEnumerable or Icollection can be serialized.

  • Classes that implement IDictionary, such as HashTable cannot be serialized.

  • You can't explicitly indicate which fields or properties are to be serialized into XML and which are to be ignored by serializer.

ASP.NET WCF services use DataContractSerializer in System.RunTime.Serialization namespace for serialization, which overcomes all the limitations of XmlSerializer mentioned above.

Some more Differences between WCF and Web 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


[ServiceContract] 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, 16 January 2016

Calling Cross Domain WCF Service using Jquery

From last couple of days, I was trying to call a wcf service using jquery that is hosted in different domain. But every time I was failed to call wcf service from different domain. After spending much time on R&D, I found the solution and the reason why I was unable to call cross domain wcf service.

Whenever you try to call a cross domain WCF Service by javascript or jquery, it behaves differently with different browsers. When you want to perform "POST" or "GET" request on cross domain wcf service or normal service using jquery/javascript or ajax, the browser actually sends an "OPTIONS" verb call to your wcf service that is not mention in your wcf method attribute. We mention there "POST" or "GET" to call a wcf service method. Hence we get error to call cross domain wcf service. We find the following request and response headers in firefox when we try to call wcf service.

Request Headers



  1. OPTIONS http://myserver/MyService.svc/GetStates HTTP/1.1

  2. Host: 192.168.4.156 User-Agent: Mozilla/5.0 (Windows NT 6.0; WOW64; rv:13.0) Gecko/20100101 Firefox/13.0

  3. Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8

  4. Accept-Language: en-us,en;q=0.5

  5. Accept-Encoding: gzip, deflate

  6. Proxy-Connection: keep-alive

  7. Origin: http://192.168.4.156:90

  8. Access-Control-Request-Method: OPTION

  9. Access-Control-Request-Headers: content-type

  10. Pragma: no-cache

  11. Cache-Control: no-cache

Response Headers



  1. HTTP/1.0 405 Method Not Allowed

  2. Cache-Control: private

  3. Allow: POST

  4. Content-Length: 1565

  5. Content-Type: text/html; charset=UTF-8

  6. Server: Microsoft-IIS/7.0

  7. X-AspNet-Version: 4.0.30319

  8. X-Powered-By: ASP.NET

  9. Access-Control-Allow-Origin: *

  10. Access-Control-Allow-Headers: Content-Type

  11. Date: Fri, 04 May 2012 12:05:17 GMT

  12. X-Cache: MISS from c1india.noida.in

  13. X-Cache-Lookup: MISS from c1india.noida.in:3128

  14. Via: 1.0 c1india.noida.in:3128 (squid/2.6.STABLE21)

  15. Proxy-Connection: close

In above request headers the method is "OPTION" not "POST" and the response headers has content-type "text/html; charset=UTF-8" instead of "json;charset=UTF-8". To change these options we need to do some changes in web.config of hosted wcf service.

Configure WCF Cross Domain service



  1. namespace CrossDomainWcfService

  2. {

  3. [DataContract]

  4. public class Supplier

  5. {

  6. [DataMember] public string Name;

  7. [DataMember] public string Email;

  8. }

  9. [ServiceContract(Namespace = "")]

  10. [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

  11. public class MyService

  12. {

  13. [OperationContract]

  14. [WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]

  15. List GetSuppliers (int OrgID)

  16. {

  17. // Fetch data from database var q= (from tbl in mobjentity.Customer

  18. where tbl.OrgID=OrgID).ToList();

  19. Listlst= new List();

  20. foreach(var supp in q)

  21. {

  22. Supplier msupp=new Supplier();

  23. msupp.Name=supp.Name;

  24. msupp.Email=supp.Email

  25. //Make Supplier List to retun

  26. lst.Add(msupp);

  27. }

  28. return lst;

  29. }

  30. }

  31. }

WCF Service Web.config



  1. <system.webServer>

  2. <modules runAllManagedModulesForAllRequests="true" />

  3. <httpProtocol>

  4. <customHeaders>

  5. <add name="Access-Control-Allow-Origin" value="*" />

  6. <add name="Access-Control-Allow-Headers" value="Content-Type" />

  7. </customHeaders>

  8. </httpProtocol>

  9. </system.webServer>

  10. <system.serviceModel>

  11. <behaviors>

  12. .

  13. .

  14. .

  15. </behaviors>

  16. <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

  17. <standardEndpoints>

  18. <webScriptEndpoint>

  19. <standardEndpoint name="" crossDomainScriptAccessEnabled="true" />

  20. </webScriptEndpoint>

  21. </standardEndpoints>

  22. <services>

  23. .

  24. .

  25. </service>

  26. </services>

  27. <bindings>

  28. .

  29. .

  30. </bindings>

  31. <client>

  32. .

  33. .

  34. </client>

  35. </system.serviceModel>

Global.asax Code


You can also define your hosted service web.config setting in Global.asax file. If you have defined setting in web.config then there is no need to do here.

  1. protected void Application_BeginRequest(object sender, EventArgs e)

  2. {

  3. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin" , ”*”);

  4. if (HttpContext.Current.Request.HttpMethod == "OPTIONS" )

  5. {

  6. //These headers are handling the "pre-flight" OPTIONS call sent by the browser

  7. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods" , "GET, POST" );

  8. HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers" , "Content-Type, Accept" );

  9. HttpContext.Current.Response.AddHeader("Access-Control-Max-Age" "1728000" );

  10. HttpContext.Current.Response.End();

  11. }

  12. }

Wcf calling using Jquery



  1. $.ajax({

  2. type: "Post"

  3. url: "http://www.yourdomain.com/MyService.svc/GetSuppliers", // Location of the service

  4. data: '{"OrgID"="1"}', //Data sent to server

  5. contentType: "application/json;charset-uf8", // content type sent to server

  6. dataType: "json", //Expected data format from server

  7. success: function (msg) {

  8. //Implement get data from service as you wish

  9. },

  10. error: function (err) {

  11. // When Service call fails

  12. }

  13. });

Note



  1. You can define cross domain setting either in web.config or in global.asax file of your wcf service.

  2. For running the code, make a virtual directory/web application on IIS and map the code folder to it.

Summary

In this article I try to explain cross domain wcf service calling with example. I hope after reading this article you will be able to call cross domain wcf service. I would like to have feedback from my blog readers. Please post your feedback, question, or comments about this article. You can download demo project from below link.

Saturday, 4 April 2015

How To Create WCF Rest Services In Asp.Net

Representational State Transfer (REST):



  • Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.


  • REST is very lightweight, and relies upon the HTTP standard to do its work. It is great to get a useful web service up and running quickly. If you don't need a strict API definition, this is the way to go. REST essentially requires HTTP, and is format-agnostic (meaning you can use XML, JSON, HTML, whatever).

Why SOAP -


Basically SOAP web services are very well established for years and they follow a strict specification that describes how to communicate with them based on the SOAP specification. SOAP (using WSDL) is a heavy-weight XML standard that is centered around document passing. The advantage with this is that your requests and responses can be very well structured, and can even use a DTD. However, this is good if two parties need to have a strict contract (say for inter-bank communication). SOAP also lets you layer things like WS-Security on your documents. SOAP is generally transport-agnostic, meaning you don't necessarily need to use HTTP.

Why Rest Services -


Now REST web services are a bit newer and basically look like simpler because they are not using any communication protocol. Basically what you send and receipt when you use a REST web service is plain XML / JSON through an simple user define Uri (through UriTemplate).

Which and When (Rest Or Soap) -


Generally if you don't need fancy WS-* features and want to make your service as lightweight, example calling from mobile devices like cell phone, pda etc. REST specifications are generally human-readable only.

How to Make Rest Services -


In .Net Microsoft provide the rest architecture building api in WCF application that manage request and response over webHttpBinding protocol here is the code how to create simple rest service through WCF (Only GET http method example).

We can also make our own rest architecture manually through http handler to creating the rest service that would be more efficient and simple to understand what going on inside the rest, we’ll discuss it further at next post.

Just add new WCF application/services or make a website and add a .srv (WCF Service) in it.

CS Part: (IRestSer.cs, RestSer.cs) -


Below is the rest service contract (interface) part and implementation of contract methods part, It is required to add WebInvoke or WebGet attribute on the top of the function that we need to call through webHttpBindingprotocol,

Methods include Get, Post, Put, Delete that is http methods.

UriTemplate is required to make fake host for rest service, Uri address actually not exist in real time it is created by WebServiceHostFactory at runtime (when application starts).

Value inside curly braces ({name},{id}) matches with function parameter and Rest api passes value at runtime to corresponding parameters.
IRestSer.cs Part: (Contract Interface):

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.ServiceModel.Web;

[ServiceContract]

public interface IRestSer

{

[OperationContract]

[WebInvoke(Method = "GET", UriTemplate = "/FakeUrl/P1={Name}",

ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json)]

string SayHello(string Name);

}

RestSer.cs Part (Implementation of contract)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

public class RestSer : IRestSer

{

public string SayHello(string Name)

{

return "Hello " + Name;

}

}

RestSer.svc Part -


Below is the Rest service .svc part where you have to mention factory attribute and set the value (System.ServiceModel.Activation.WebserviceHostFactory) as shown below -

This is required for communication with UriTemplate and makes fake URL host according to UriTemplate.



<%@ ServiceHost Language="C#" Debug="true" Service="RestSer"Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

Need to change binding protocol (webHttpBinding) as rest service call over webHttpBinding protocol only.



<system.serviceModel>

<behaviors>

<serviceBehaviors>

<behavior name="RestBehavior">

<serviceMetadata httpGetEnabled="true" />

<serviceDebug includeExceptionDetailInFaults="false" />

</behavior>

</serviceBehaviors>

</behaviors>



<services>

<service behaviorConfiguration="RestBehavior" name="Rest">

<endpoint address="" binding="webHttpBinding" contract="IRest">

<identity>

<dns value="localhost" />

</identity>

</endpoint>

</service>

</services>

</system.serviceModel>

Calling Through direct Uri / Ajax request :


(Make Virtual directory in IIS named RestExample) 





function CallgetJSON() {

$.getJSON("http://localhost/RestExample/RestSer.svc/FakeUrl/P1=Vivek",

function(data) {

alert(data);

});

}