HI WELCOME TO SIRIS
Showing posts with label wcf tutorials. Show all posts
Showing posts with label wcf tutorials. Show all posts

Understanding different types of WCF Contracts

Leave a Comment
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.


Calling Cross Domain WCF Service using Jquery

Leave a Comment
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.