Friday, August 15, 2014

System.BadImageFormatException: Could not load file or assembly(Windows service)

Recently I have created a windows service and I wanted to to install that service to the my QA server.for that I used InstallUtil command.So for that below command in my command prompt.


But that command failed with below message

System.BadImageFormatException: Could not load file or assembly '{WriteOffService.exe}' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Then after my check dependencies those were placed fine.After I search I found the reason for this. Smile

I have complied my application according to the 32 bit configuration and I used 64 Bit installUtil to the install application. after I installed it using 32 bit installUtil and its worked as expected.

After you install .Net framework(in my case it is version 4.0) its created the two separate folders for 32 bit and 64 bit.In side those folders for according to the Framework version

Intallation root:\Windows\Microsoft.NET\


(here you can see two different folders Framework(32) and Framwork64(64)).That each folder contains two InstallUtil versions according to the .Net Framework version.


64 bit version


32 bit version

Monday, April 7, 2014

WCF Discovery : Ad Hoc Discovery Client

WCF Discovery is a new feature which was shipped with WCF 4.0.WCF discovery is an implementation of the OASIS WS-Discovery specification.Think a scenario where  client application has the address of a specific service hard-coded into its configuration, then if that service moves, becomes temporarily unavailable, or is just too busy to handle requests, the client will not be able to communicate with it. WCF provides discovery and routing to address these issues. By implementing discovery client Application can locate the specific service address dynamically. As well as service can broadcasts its status to the all clients when service goes down or up.

There are two ways to implement WCF discovery.

  • Add Hoc Discovery
  • Manage Discovery

In this example I m going to explain Add Hoc Discovery client.In this client, service address not hard coded.Instead of that setting up the client endpoint address dynamically.

How this works ?

In Adhoc model clients send Probe message to the network .This message contains the information about the service which it wishes to connect. After service receives a Probe request, it can examine its contents, and if the probe matches the contract implemented by the service, it can respond to the client with a ProbeMatch message. TheProbeMatch message contains the service addressing information that the client needs to connect to the service.Client message uses the UDP protocol to send the probe message.

When implementing in order to  support above model service need to add specific endpoint call udpDiscoveryEndpoint and Service Discovery behavior to the service behaviors

what is udpDiscoveryEndpoint – This is a standard endpoint which used to implement the ad hoc mode of discovery.

<service name="Discovery.PTSService" behaviorConfiguration="discoveryBehaviour">
<endpoint address="" binding="basicHttpBinding" bindingConfiguration="httpBinding"
contract="Discovery.IPTSService" />
<!—new discovery endpoint-->
<endpoint kind="udpDiscoveryEndpoint"/>

What is Kind ?

udpDiscoveryEndpoint is standard endpoint .if we need to use standard endpoint we have to use kind instead of name. for more information

<behavior name="discoveryBehaviour">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />

<!-- service dicovery behaviors -->
<serviceDiscovery />

Additionally we can set the scope for the service endpoint behaviors.which Adds the scope information for the endpoint that can be used in matching criteria for finding services.

Now our service is completed.(please make sure service is up and running)Now move the client implementation.


Client need to have reference to the System.ServiceModel.Discovery and your service.


static void Main(string[] args)
//initialize new discovery Client with UdpDiscoveryEndpoint
DiscoveryClient client = new DiscoveryClient(new UdpDiscoveryEndpoint());

// define the find criteria with serivce type
FindCriteria criteria = new FindCriteria(typeof(IPTSService));

// then clinet .Find
FindResponse services = client.Find(criteria);


Additionally FindCriteria can set the time out for service discovery. whether criteria can find service or not its return the output after the specified time.

criteria.Duration = TimeSpan.FromSeconds(50);

Lets run and see what happens.I have put watcher to the my services object..


Now you can see Find response contains all the required for the service invocation.

Thursday, April 3, 2014

The type 'System.ServiceModel.Routing.RoutingService', provided as the Service attribute value in the ServiceHost directive, or provided in the configuration element system.serviceModel/serviceHostingEnvironment/serviceActivations could not be found

Recently I have created WCF router service and deployed to IIS. But once I run the my router service its gives me above error Sad smile.Normally this kind of errors happen when service couldn't find the service host reference. but in my router service its seems ok .

<%@ ServiceHost Language="C#" Debug="true" Service="System.ServiceModel.Routing.RoutingService" %>

Then I use full qualified name instead of the name as below.Bingo then its works Smile 

<%@ ServiceHost Language="C#" Debug="true" Service="System.ServiceModel.Routing.RoutingService,System.ServiceModel.Routing, version=, Culture=neutral,PublicKeyToken=31bf3856ad364e35"  %>

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);
   5:     var message1 = buffer.CreateMessage();
   8:     buffer.Close();
  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).

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


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


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


Open proxy file.


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


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();
   4: // create user nam token
   5: UsernameToken userToken = new UsernameToken("username", "password", PasswordOption.SendPlainText);
   7: // get reference to the proxy request context.
   8: SoapContext requestContext = soupClinet.RequestSoapContext;
  10: // then add user token to the security context.
  11: requestContext.Security.Tokens.Add(userToken);
  13: try
  14: {
  15:     var result = soupClinet.deleteIssue(rptIssue);              
  16: }
  17: catch (Exception ex)
  18: {
  19:     Console.WriteLine(ex.Message);
  20: }
  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. 


Then go the advanced.


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

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.


After deploy to the IIS(with out svc).




For additional information please refer :

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.