Wednesday, April 2, 2014

This message cannot support the operation because it has been copied

In order to implement few validations I have written separate method which expects message instance as parameter. In side that method I process the  input message . but once I try to run my service it throws above error and terminates the process Sad smile. after spending some time with the issue I could identify the issue.

according to the MSDN The body of a Message instance can only be consumed or written once. but I have tried several times to read message instance inside my validation logic.

from MSDN

“You can access the body of a Message only once, regardless of how it is accessed. A message object has a State property, which is initially set to Created. The three access methods described in the preceding list set the state to Written, Read, and Copied, respectively. Additionally, a Close method can set the state to Closed when the message body contents are no longer required. The message body can be accessed only in the Created state, and there is no way to go back to the Created state after the state has changed.”

There fore we need to use CreateMessageCopy method for reading the message.

   1: public bool Logic(Message message)
   2: {
   3:     MessageBuffer buffer = message.CreateBufferedCopy(Int32.MaxValue);
   4:  
   5:     var message1 = buffer.CreateMessage();
   7:  
   8:     buffer.Close();
   9:  
  10:     return true;
  11: }

Bingo its works Smile

Tuesday, April 1, 2014

How to add user name token to the soap header :VS2012

When calling secure old asmx web service using  c# we cant directly add user name token to the soap header like WCF.we need to have Microsoft.Web.Services(Version) library.Microsoft has not shipped this library along with the .Net framework.Instead of that Microsoft has provided package called Web Services Enhancements which is a product that enables you to build secure Web services quickly and easily.

There are few versions for WSE. Downloaded and install  latest version from below link(3.0).

http://www.microsoft.com/en-us/download/details.aspx?id=14089

after installed go to the below location.(my DEV machine is win7 64 bit version- path may change according to the your windows version)

image

Then add Microsoft.Web.Service3.dll reference to your project.

image

Then add the web service reference to the project and open reference.cs file.(to open that click show all files)

image

Open proxy file.

image

you can see our generated soap class inherited from SoapHttpClientProtocol. we need to change it to the Microsoft.Web.Services3.WebServicesClientProtocol .

image

Now we are done with the proxy class. then need to add the blow code to the web service client.

   1: TestHost.ManufacturingSOAP soupClinet = new TestHost.ManufacturingSOAP();
   2: TestHost.deleteIssueRequest rptIssue = new TestHost.deleteIssueRequest();
   3:  
   4: // create user nam token
   5: UsernameToken userToken = new UsernameToken("username", "password", PasswordOption.SendPlainText);
   6:  
   7: // get reference to the proxy request context.
   8: SoapContext requestContext = soupClinet.RequestSoapContext;
   9:  
  10: // then add user token to the security context.
  11: requestContext.Security.Tokens.Add(userToken);
  12:  
  13: try
  14: {
  15:     var result = soupClinet.deleteIssue(rptIssue);              
  16: }
  17: catch (Exception ex)
  18: {
  19:     Console.WriteLine(ex.Message);
  20: }
  21:  
  22: Console.Read();

WCF Asynchronous : Event Base pattern

When developing applications some time we have deal with the long running tasks.During the long running process its very import to to keep the UI responsive and feed updates to the user.When we comes to the service oriented architecture some times we have to deal with the long running services.Then UI does not hang while service works.To avoid such a behaviors we can use asynchronous pattern.

Basically WCF supports three type of Async patterns.

  • The event-based asynchronous pattern .
  • The IAsyncResult asynchronous pattern .
  • The task-based asynchronous pattern.

This simple example is related to the event based async pattern.

first we need to implement the service.

   1:  public class LongRunner : ILongRunner
   2:      {
   3:          public string InitiateLongRunner()
   4:          {
   5:              // for the sake of the simplicity im just delaying the method execution.
   6:              Thread.Sleep(TimeSpan.FromSeconds(5));
   7:              return "Long running process has completed";
   8:          }       
   9:      }



Service contract.


   1:   [ServiceContract]
   2:      public interface ILongRunner
   3:      {
   4:          [OperationContract]
   5:          string InitiateLongRunner(); 
   6:      }



Please make sure your service up and running.


In this method we don’t need to add any additional coding to service implementation in order to support the asynchronous behavior.


Client proxy creation.


Add service reference. 


image


Then go the advanced.


image


Then select “Generate asynchronous operation” radio button. (This will add async method to the service WSDL.)


Initiate the service call.


   1:  class Program
   2:      {
   3:          static void Main(string[] args)
   4:          {
   5:              using (MyClient.LongRunnerClient client = new MyClient.LongRunnerClient())
   6:              {
   7:                  // register the event. this event fires when the service operation has completed.
   8:                  client.InitiateLongRunnerCompleted += client_InitiateLongRunnerCompleted;
   9:   
  10:                  // call the long running operations
  11:                  client.InitiateLongRunnerAsync();
  12:                  Console.WriteLine("Long runner has started.");
  13:                  Console.WriteLine("Request is processing.");
  14:                  Console.Read();
  15:              }
  16:          }
  17:   
  18:          /// <summary>
  19:          /// Handles the service reply.
  20:          /// </summary>
  21:          /// <param name="sender"></param>
  22:          /// <param name="e"></param>
  23:          private static void client_InitiateLongRunnerCompleted(object sender, MyClient.InitiateLongRunnerCompletedEventArgs e)
  24:          {
  25:              Console.WriteLine(e.Result.ToString());
  26:          }
  27:      }



In Line 11 uses the async method than the original one . When we generate the WSDL including asynchronous methods, async method name came as original method name + “async”  word.


result can be taken from the async method handler event args.(e.Result).

Deploy WCF service without SVC file in IIS and WAS

Normally when we going to host WCF service in IIS or WAS need to have svc file. The Service.svc file is an XML-based file that must include an @ServiceHost directive. The directive identifies your
service, and it should include attributes that identify the service code language and the name
of the service.

But think a scenario where you have lots of services in a enterprise environment.Then you have to maintain lot of svc files.Its adds extra penalty to the developer as well as the deployment engineer.fortunately WCF 4.0  has shipped with new future called Configuration based activation which is capable for overcome this problem.

There are lo of WCF 4.0 features.Please refer MSDN . http://msdn.microsoft.com/en-us/library/dd456789(v=vs.100).aspx

When using CBA we don’t need to use and svc file instead of that Configuration-based activation takes the metadata that used to be placed in the .svc file and places it in the Web.config file.It use <serviceHostingEnvironment>/<serviceActivations> tags.

let see below example.we need to add below code to the web.config file.

CBAimage1

After deploy to the IIS(with out svc).

iis

finally

CBDemo

For additional information please refer : http://msdn.microsoft.com/en-us/library/ee358764(v=VS.110).aspx

Wednesday, January 29, 2014

Never throw ex just throw the exception.

today I got one error report from one of our users.then I examined the my log files. oops error stack traces were not logged properly.after few minutes I figure out what happen were there.In my some of methods I catch the exception and  throw ex instead of just throw.

from Stack over flow marc gravell

  • throw ex resets the stack trace (so your errors would appear to originate from HandleException)
  • throw doesn't - the original offender would be preserved.

Wednesday, October 30, 2013

Unable to update the EntitySet because it has a DefiningQuery and no element exists in the element to support the current operation.

 

Recently I got this error when I try to update table using Entity framework 5.

Cause :Reason for that is the target table does not have the primary key.So need to add the primary key to the target table.

Happy coding Smile

Thursday, October 24, 2013

LINQ to Entities does not recognize the method 'Boolean IsNullOrWhiteSpace(System.String)' method

 

recently I have used below query to get some filterded details from my table.

dbContext.ttable.Where(r => string.IsNullOrWhiteSpace(r.field))






but when I try to run above code snipped I got


“LINQ to Entities does not recognize the method 'Boolean IsNullOrWhiteSpace(System.String)' method, and this method cannot be translated into a store expression."”


after few minutes searching found the reason for that.


My query return type is IQueryable<ttable>.So this type is optimized to the deliver an optimized query.In this context all C# methods are not supported.There for I have to change the query like this and then it works Smile


dbContext.table.where.(!(b.field == null || r. b.field.Trim() == ""))