Showing posts with label wcf tutorials. Show all posts
Showing posts with label wcf tutorials. Show all posts

Understanding Session Management in WCF

WCF manage session by creating the instance of the service class. These created instance(s) handle the incoming service request. In WCF, session is the way of managing the services instance(s) so that server can used these instances in an optimized way. At server side InstanceContext class is used to manage service class instance.
In WCF, there are three Instance Management way as given below:
  1. Per Call

    In this way, each request is served by a new service instance. It means a new service instance is created for each request and destroyed after the request is served.

    This make your WCF service stateless means you can’t maintain states between WCF calls.
  2. Per Session

    In this way, each and every client requests are served by a new single service instance. It means a new service instance is created for a client all requests and destroyed after the client finished its activity.

    This way make your WCF service state-full means you can maintain states between WCF calls.
  3. Single

    In this way, all clients’ requests are served by a single service instance. It means a single service instance is created to handle all the clients’ requests and never destroyed after serving the request.

    This makes your WCF service data shared globally.

How WCF Session is different from Asp.Net Session?

WCF Session management is different from Asp.Net Session Management in the following ways:
  1. WCF Sessions are created and terminated by service client.
  2. Server use session to manage service instances, not to store some general data like Asp.Net.
  3. WCF Session does not mainly rely on Session ID like Asp.Net, a particular field with in the header or body of a group of messages can also be considered as a part of session.
  4. There may be different Session ID at client and server side unlike Asp.Net.
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.

Error code 12031 in Ajax enabled wcf

From last couple of days I was trying to call a ajax enabled wcf service method with the help of jquery. But each and every time I am getting the error code 12031 returned by the service. I did googling for this error but I was unable to find the solution. After spending much time on R&D, I found the reason why I wa geeting this error.
In this article, I am going to share my experience with you so that you will be able to resolve this error in ajax enabled wcf service. I have the below service and code for calling wcf.

WCF Service

 namespace WCFBAL
 public class Employee
 public int EmpID;
 public string Name;
 public int Salary;
 public DateTime JoiningDate;
 [ServiceContract(Namespace = "")]
 [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
 public class WCFBALService
 [WebInvoke(Method = "POST")]
 public Employee GetEmpInfo(int mEmpID)
 //suppose you have a list of employee like as in the database
 List lst = new List() 
 new Employee { EmpID = 1, Name = "Deepak", Salary = 12000, JoiningDate = Convert.ToDateTime("11/05/2011") },
 new Employee { EmpID = 2, Name = "Mohan", Salary = 18000},
 new Employee { EmpID = 3, Name = "Mohan", JoiningDate = Convert.ToDateTime("06/10/2011") }
 var q = lst.Where(m => m.EmpID == mEmpID).FirstOrDefault();
 Employee mobjEmp = new Employee();
 if (q != null)
 mobjEmp.EmpID = q.EmpID;
 mobjEmp.Name = q.Name;
mobjEmp.Salary = q.Salary; // comment this line to expect same error 
 //The no error will be raised since "Salary" field is of int type and default value of int variable is "0", so zero value will be assigned to it. 
 mobjEmp.JoiningDate = q.JoiningDate; // comment this line and provide mEmpID=1 to raise error 
 //The error will be raised since "JoiningDate" field is not being serialized because this of DateTime and this has no default value and not assign any value to it.
 return mobjEmp;
 catch (Exception mex)
 return null;

WCF Service Method Calling Code

 <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script> <script type="text/javascript">
 $('#btn').live('click', function () {
 // debugger;
 var value = $('#txtEmpID').val();
 if (value != '') {
 var strJSONFilterCriteria = '{"mEmpID":"' + value + '"}';
 $.ajax({ type: "POST", contentType: "application/json; charset=utf-8",
 url: '<%=ViewState["WCFBalUrl"]%>' + '/GetEmpInfo',
 data: strJSONFilterCriteria,
 dataType: "json",
 error: function (msg) {
 // debugger;
 alert('Service call failed: ' + msg.status + ' Type :' + msg.statusText);
 success: function (msg) {
 var str = "Emp ID:" + msg.d.EmpID + "\n";
 str += "Emp Name:" + msg.d.Name + "\n";
 str += "Emp Salary:" + msg.d.Salary + "\n";
 //str += "JoiningDate:" + new Date(parseInt(msg.d.JoiningDate.substr(6))) + "\n";
 } }); }
 return false;
 WCF Error Code 12031
 To learn more about Dot Net Tricks visit <a href="http://www.dotnet-tricks.com" title="Dot Net Tricks ">
 Enter Employee ID (1-3)
 <asp:TextBox ID="txtEmpID" runat="server" ClientIDMode="Static"></asp:TextBox>
  <asp:Button ID="btn" runat="server" Text="Get Info" ClientIDMode="Static" />

I hope you will enjoy this trick while programming with Ajax enabled 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

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: 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:
  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. });


  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.
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.