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

Tuesday, April 12, 2022

Azure @ Enterprise - WCF netNamedPipe binding inside Windows container

Recently I was into serious discussions on containerizing 15+ years old distributed applications developed using the .Net Framework and hosted in IIS web server. The first suggestion or the approach coming to all our minds is to migrate to .Net 6 and containerize using Linux containers. Nobody thinks about Windows containers. But unfortunately, we need to think about containerizing it to Windows containers. We are not going to discuss the merits and demerits of Windows containers in this post or the rationale for that thought. But one of the technical tasks that will come if we use Windows containers.

Please note this needs some basic understanding of WCF (Windows Communication Foundation)

Problem

The current system has the below characteristics

  • It uses netNamedPipeBinding to expose internal services in every IIS box. 
  • The HTTP front-facing apps and APIs consume the internal net.pipe services to get things done.
  • The internal services are also hosted inside IIS. 

If we move to Windows containers one approach to solve this is to extract the internal services and host them as independent containers and use net.tcp binding to establish communication. It is simply that the net.pipe binding only works inside the machine.

But let us see how can we have netNamedPipe services inside the same container as the front-end services and establish the communication between services using net.pipe?

Challenges

  • The base image provided by Microsoft doesn't have support for hosting net.pipe services.
  • The UI tooling is limited when we are in the container world compared to IIS in the Windows server machines. We should have a good grip on using AppCmd command for IIS management or the PowerShell modules such as WebAdministration or IISAdministration used to manage IIS.

Solution

It is nothing fancy. This will work if we get the Dockerfile right. We need to enable the netNamedPipe binding at the machine level and set the bindings and protocols at the IIS level.

I am not giving many details in this post as the repo will get more updates into the readme.md file.

Happy coding.

Tuesday, August 13, 2019

System.Diagnostics logging in .Net - Trace sources

As developers, we often need to work with network issues. The first step is to finding out there is a network issue such as delay or package loss. This can be found by looking at Wireshark. But Wireshark needs some expertise. Also, it needs installation and mostly a restart after installation. When working in production environments it would be difficult to restart. But the other side is we can analyze without any changes to the application as setting diagnostics source needs application config changes.
But if we just consider the expertise needed for Wireshark, a better way is to collect some svc logs using Diagnostics. If required go for Wireshark as the second step of the analysis.

Diagnostics sources related to Network

We are not going to create another list. Below are the links to already existing tutorials

General networking

https://docs.microsoft.com/en-us/dotnet/framework/network-programming/how-to-configure-network-tracing
https://blogs.msdn.microsoft.com/waws/2017/03/14/how-to-get-a-system-net-trace-of-your-c-web-job/

WCF

Legacy ASMX

Other diagnostic sources

Since diagnostics source tracing is .Net feature, there are other diagnostics sources as well useful in different scenarios. Below are some collections.

https://stackoverflow.com/questions/2464071/what-is-the-list-of-trace-sources-supplied-by-the-net-framework

Unfortunately, it seems there is no official link of the full list of trace sources.

Tuesday, January 9, 2018

WCF - Concurrency, InstanceContextMode and SessionMode & request handling behavior

Though WebAPI is penetrating the service world in .Net WCF still has a space in .Net. The main reason is the support for protocols other than http and there are lot of legacy systems out there which has to be maintained till the world fully moved to Cloud native.

WCF is easy to develop but when it comes to production, there are so many internal things to be known than just writing the service. The major area to be known before putting any WCF service is how the service is going to serve requests. Will there be one service object? How many requests will be processed in parallel? In there are more than one requests getting processed how many service objects will be there to process? Is it one to one or one to many? If it is one service object processing  many requests what is means to thread safety? Service object here means the object of class which implements the service contract interface? Hope everyone knows who creates the object of implementation class.

There are so many articles out there which explains how the service process requests. So this post is to consolidate all in one place to avoid googling.

MSDN Article 1 & Article 2 - These are the best article if someone have enough understanding about the concept. If someone is really fresh to WCF this is not a great place to start

Sivaprasad Koirala on Instancing & concurrency - This is good place to start for freshers. He explains with diagrams and there is a good sample which can be used to understand the behavior. But it talks only instancing and concurrency. When instancing combined with Concurrency mode and Session, the behavior will change.

If we are in hurry and have to understand the behavior quickly the best site is given below.

https://whinery.wordpress.com/2014/07/29/wcf-sessions-instancing-and-concurrency-explained/

It explains with combinations and tell what happens in each combination. But the unlucky blog post has no comments till now even after 3 years.

It is not ending here. There is throttling behavior which might need to be tweaked. Also the security mode which gets enabled automatically for some bindings though we don't need it and reduce throughput.

Tuesday, August 29, 2017

Azure Application Insights - End to end correlation from Angular to internal WCF services

Azure AppInsights is one of the PaaS offering which can be easily configured to our application and leverage capabilities. And it really works without any changes in our application. But does it helps us more than any other tools? May be yes with default setup. We will really love it if we can get end to end correlation to understand what is happening in our system. Production debugging will be a breeze with correlation. 

This post is talking about how can we correlate activities happening in different tiers of our system and see it in one place. Lets take a scenario where an Angular application is interfacing with users, it calls ReST endpoints to talk to front end services and front end services communicate with other internal services. We can correlate operations originating from client side to related operations happening in the internal services.

Prerequisite

  • Basic knowledge about AngularJS 1.x
  • Knowledge about WCF services.
  • Knowledge about setting up AppInsights service

Sample setup

It is advised to download the sample from below location before reading further. Below goes the structure of sample.

AngularJS application just does one thing. Finding the area of circle if we give radius. For finding area, it calls a ReST web service.
It sends one event during startup. Another one during calculating the area ie when calling the FronEndWCFService. These are custom AppInsights events

FronEndWCFService is a simple WCF service hosted using webHttpBinding to get ReST end points. It calculates the area using the parameter radius. It don't know the value of pi. It dependent on InternalService to get the value of pi. During the calculation it sends some custom events/operations to AppInsights.

InternalService is hosted using net.pipe binding. It has one method which returns the value of Pi. It also sends some custom events to AppInsights.

The above 3 components are hosted inside IIS and enabled with AppInsights for default system events.

Running the sample

  • Make sure the 3 web applications are hosted in IIS.
    • The web application has to net.pipe binding to host InternalService.
    • Try to browse the service Urls.
  • Give the Url of InternalService in the web config of FrontEndWCFService so that it can call.
  • Obtain AppInsights instrumentation key by either creating a new instance in Azure or copy from existing AppInsights instance. Replace this key into web applications. Better use visual studio search and replace and the word to replace with key is {Your Key} .There are 3 files to get the instrumentation key. 
    • /AngularClient/Views/Shared/_Layout.cshtml
    • /FrontEndWCFService/ApplicationInsights.config
    • /InternalService/ApplicationInsights.config
  • Run the AngularClient application in browser.
    • During the application load, it will log "Custom init event from JS"
    • When we give the radius in the text box and click on button it will log "Custom event from JS before service call"

Viewing the AppInsights

It may take some time to get the entries reflected in the AppInsight in the Azure portal. It is better to go to the analytics portal of ApplicationInsight instance and view the results. In the analytics portal, the details can be seen as follows.

The entries highlighted in the name column are the custom events generated by different tiers in the system. Along with custom events the system will generate event if AppInsights collectors are attached to the processes. That can be done by connecting interceptors in the WCF or HttpModules in Web request pipelines.

Understanding correlation results

The operation_id column is the id which really correlate the operations. The id has to be unique and the parent_id can be any id used previously. It can be a tree of related events.

Don't get confused on the term 'events' used here. AppInsight can accept events, operations, traces etc...For easy reference term event is used.

Q&A

How does a web request from Angular gets correlated with servers

When we send web request from Angular or any client if we send http header "Request-Id" it will be treated as operation_id by server side, if we have the AppInsight request interceptors

Why the sample has 2 methods in Angular to write custom AppInsights

When the application is getting initialized, the appInsights object may not have the context ready.If so we have to put into queue. Once the context is initialized, we can use it to set operation_id. At that point the queue will be null.

Should I write any code for intercepting incoming web/WCF requests to read correlation data?

No we just need to use already available nuget packages and setup our web.config appropriately.

Should I write any code for intercepting the out going web/WCF requests to write correlation data?

No we just need to use already available nuget packages and setup our web.config appropriately.

References

https://docs.microsoft.com/en-us/azure/application-insights/application-insights-correlation
https://github.com/Azure/diagnostics-correlation
https://github.com/Microsoft/ApplicationInsights-JS
https://github.com/aspnet/Microsoft.AspNet.TelemetryCorrelation
https://mitra.computa.asia/article/msdn-modifying-and-filtering-telemetry-appinsights-javascript-sdk-telemetry-initializer

Tuesday, September 20, 2016

IPC with SendMessage between WPF and WinForms apps

Communicating between processes is essential part of every big systems which we generally call as Inter Process Communication. If its large distributed systems the processes will be in different computers which we classify as servers and clients. Often we use http / http(s) based or other socket based communication mechanisms to do the job. In .Net world most of the people use WCF.

But in some cases there will be big systems running on same computer as separate processes and would like to communicate each other. We can use WCF here also with net.pipe binding. Since its same machine there are some more available options. Lets see what are those options. This post is about such an alternative which uses SendMessage API provided by Windows OS.

Clipboard

One of the dangerous forms of communication. Dangerous as user or any other application can copy new data to clipboard before our intended process reads data. But I have seen enterprise systems which uses this technique and working well for years.

EventLog

The sender can write to event log and the receiver subscribe to the event log entries to receive message. This will leave a trace of what has send back and forth between apps. But we should never use this for secure communication unless encrypted.

Standard In and Out of processes

One process can write to StdIn stream of another process and other can write to sender's StdId for two way communications. I have used this technique in one of my recent projects as it spawns processes frequently where publishing a unique WCF end endpoint was little difficult to achieve.

FileWatcher

Still many systems uses this technique. If there is a designated folder for messages and files are unique, it will work. in .Net works we can use FileSystemWatcher APIs to achieve the functionality.

SendMessage

Here we leverage the SendMessage windows API function to send a message to another process. That message then will be available to the message pump of receiving application. As we know the windows apps are running based on the messaging infrastructure. In simple words, the OS sends appropriate messages to apps about what is going on (eg:MouseClicked) with required contextual data and apps just process them. Its same for WPF as well though its hidden for normal apps. But there is a way to capture the message pump in WPF apps. 

A sample has been uploaded to github which shows how communication can be established between WinForms app and WPF app using SendMessage. Since the code is the true documentation, there is no more explanation required in this post.

https://github.com/joymon/Win32IPCDemo

Happy coding.

Tuesday, April 5, 2016

What is Microservice Architecture to me?

Microservice is a buzzword in current Software engineering world. Everyone wanted to say we are building microservices or eagerly want to adopt it.

Reasons for micro services

Microservice - Bring Agile to Architecture

If we look at definition, we can see its an architectural style, where system is divided to small autonomous processes which are coupled with programming language/platform independent API. But we had similar kind of architecture in SOA (Service Oriented Architecture). They were also communicating kind of stable independent APIs. But what is the main difference or advantage.

Frequent releases

Yes the ability to release  more frequently is the key. We cannot deny other advantages that system is clean with small services which knows how to do its duty well, system can easily be built with different programming languages, scale only required components/services instead of whole system. etc...

If we remember the introduction of agile, there were so many advantages advertised. Working code over documentation, customer collaboration, responding to change were some to mention. But what is the real key? The key was 2-3 week based sprints which delivers something. As of my understanding most of the service companies adopted agile only because there will be a release in 2-3 weeks and developers will work night and weekend every 2nd week. In waterfall, the night and weekend parties were once in 6 months. Most of the places only the concept of sprint was taken but other concepts like maintaining backlogs, avoiding documentation over code were discarded. There would be no release happened in the world without documentation saying that code is working. 

What is there in Microservice? Independent teams who take ownership of small services. The size of the service, kind of relates to the size of the team who delivers it. And deliver daily, twice a day or if possible hourly.

Yes most of the places we can see an emphasis on TDD when adopting Microservice. But that is something might be discarded to rush to release.

What is the bottom line? The architecture will be agile. A Microservice could be introduced at any time in the development phase. Servers are going to be flooded with services. The complexity of the system is going to be in the orchestration of Microservices.

Design Microservice

Whatever we think, the Microservices architecture is a reality and soon most of our apps are going to be Microservice based. As the software engineering is still evolving, only fittest will survive. Currently it seems Microservice is a fittest one. Of course there are some problems to which Microservices approach is not the best solution.

Here lets see what are the characteristics of Microservices? 

Independent release

If a service can be released independently of the other parts of the system, it can be considered as Microservice. Sometimes the new API methods we released in the Microservice might not have any consumer components as the consumers can release only after the service release. 

The concept of independence is really important, if we want to release too often. If it depend on other components we cannot release fast & often.

Independent data store

If we want to have independent release of a service, it's data store should be independent. If there is a database table and a component release upgrade the schema causing other components to fail, we cannot consider that component as a Microservice. In short Microservice should be the only one to own it's data store. If other components in the system want to write something to the store they should call service.

Independent development team

If we want independence, probably it should be done by independent team. This is something not with the technology. Organization structure needs refactoring and is tough. 

The speed of delivery is prone to errors as well and it is advised to have development team supporting the service. If the team is shuffled after each release or members change often, they cannot support service as their own baby and the micro service architecture might feel a failure.

Independent framework/platform/language

This is not a mandatory thing. If there is a pressing need for adopting a particular technology which is different from regular technology stack, Microservice is recommended. But only if the above 3 criteria are met. Even we can have Microservice based systems with one language and technology.

Adopt only if

Do not jump just into Microservice without proper assessment and planning. If everything is independent who coordinates all these to work as a complete system which cater business need? Below are the things to make sure before jumping into Microservice world.

Defined integration guidelines between components. http(s)

If you don't have defined integration strategy of Microservices, it will simply fail. The recommended integration if through http(s) protocol if the interaction is synchronous. If the integration if asynchronous, adopt message queuing, service bus etc... But make sure there are enough design sessions and agreements before adoption.

Upfront design on the API

The real world systems / business problems are always complex. In monolithic system, we were handling the complexity in big components. But in Microservice era, the individual components are simple, but the complexity is shifted towards the interaction of services.

This requires carefully designed APIs for each Microservice. API is always like Mumbai underworld. Once we enter, there is no coming back. Once we publish an API, we don't know who are all calling it. Correcting the API and communicating the same to all consumers to redirect to new API is always costly.

Deployment is easy and automated.

We have seen one of the major advantage of Microservice is the frequent releases. Is the installation going to be done manually every time? If so we will immediately feel that the Microservice is a bad idea.

Deployment should always be automated. A continuous integration and delivery pipeline is always essential.

Strong automation testing. Prefer 100% test coverage

There is no human required for day to day deployment. They just setup the CI & CD in the beggining and system will do deployment automatically. What about testing? Are we expecting a manual tester to test all the changes before we release daily?

That's again should be automated. Developers should write proper test cases for the API. Most of the companies are employing a separate team / person for testing, is on the assumption that a developer doesn't want to break his own code or psychologically they cannot find out errors in the system what they build . When developer test, he tests only positive or usual scenarios because he knows how the system works. But here in Microservice world. we are not entertaining separate manual testing team,So how to tackle it?

Its very easy to tackle. Some other developer needs to write the tests. If the existing testing team knows how to code API tests, integration tests, they can also do. Please note we are against manual click QA. Automation QA is always welcome.

Service monitoring & management

We are talking about explosion of services. There are chances that each class/component in your existing system such as logging, caching will become a service. Some services will be versioned services, some will be cumulative/in place update. We need to add more service instances and load balance when services show load. Some might not be even used. A machine which hosted a service might go down and we need to relocate the service without zero or a little downtime. How do we deal with all these scenarios? 

The answer is a strong service monitoring and management infrastructure. Easy way is to host in cloud, where this is free with cloud provider. We don't need to develop infra management application for increasing number of machine and deploying the service to it. Or to move service from one machine to another machine etc...

Versioning, dependency management, retirement strategy

V2 of Service A may require V4 of Service B to be present in the system where V1 of Service C require V3 of Service B. This means V3 of Service B cannot be retired until Service C is retired.

Why we need to retire a service. Over the time some services will be legacy and there will be nobody calling it. But it just stays in the production environment. It is the decision of the stakeholders to retire or not. If we plan to retire everybody should be notified that, it is retired so that no new service call these retire ones.

Another interesting scenario is whether the a service say Service X should know the location of other service Y? Though the Location has many things to consider, here let's take as the url of service. If we decide to keep the location of Y in X, we cannot move the Service Y to other machine or environment. Hard coded location will cause trouble. Suppose we started with all the services on premises and due to load, if we decide to move Service Y to cloud Service X, will simply fail in calling Y.

This requires a service registry which keeps track of all the services and their dependency. This can be another service but in fixed location of course.

If you have access to production

If the development is for a product your company owns and is server based, Micro services works great. If the product is delivered as an installer to your clients, it would be really difficult to manage, as they may be still installing the morning release when you give evening release.

So basically better choose, if the CI & CD pipeline can reach till production. We can refactor the other systems to Microservice based but will never get the advantage of frequent release.

What to do with UI

Till now, we were talking mainly about services, what about UI? Are we going to deliver UI twice a day? That is something interesting and will discuss in a future post.

Disclaimer - I work in a project which have 100+ services, though we officially not adopted the Microservices architecture. It just came like that and many services are sharing same data store. We are not doing independent release of services due to data coupling. So the above view is not from a real time successful Microservie based project rather from reading and sufferings of service management.

Tuesday, November 17, 2015

Adding ReST endpoint/webHttpBinding to an existing WCF service along with basicHttpBinding

The beginning

Long long ago, in the middle of a big system, there was a WCF service who lived happily by serving its WPF based .Net client. When the service is installed in local laptop, it served the requests via net.pipe to the requests in same machine and net.tcp to the requests coming from other machines. When it was in data centers, it was accepting requests in http(s) using basicHttpBinding. In everyplace it was secured with X509 certificates. So it never got attention of attackers. In fact there were no attackers as most of the time it was inside the boundary of corporate network.

Things were good until some crazy boys came up with the idea of converting its huge WPF based business client in to HTML. Though they were excited to create HTML application they were not brave enough to generate HTML inside browser. Instead they tried to create a MVC application from which they called this service and generated HTML to sent to client. Their strategy was to not touch anything much which are working. Just create more things around the existing. Beautiful Open-Closed principle. More than that, their aim was to prove that Yes the WPF based business application can be converted to HTML.

Half the way this leadership of the team go changed. They found that its not good to have all the HTML getting generated at the server side. Why can't we generate HTML / view at client side by calling our little service completely avoiding the intermediate MVC site which was acting like proxy and generated HTML?

It went back and forth. Many meetings held at high level. People debated at high level without looking at the code. Finally in a meeting when the code was exposed in projector, everybody agreed to have a try at client side HTML generation by calling the service.

Minimal changes for ReST

The developers were believing on the policy of "Less code less defects" so they tried to expose service via webHttpBinding with only web config changes though they new the contract needs to be changed. They simply added new endpoint with webHttpBinding.


<service name="WcfService1.Service">
  <endpoint address=""
            binding="basicHttpBinding"
            contract="WcfService1.IService"/>
  <endpoint address="rest"
            binding="webHttpBinding"
            contract="WcfService1.IService"/>
</service>


When they first called our little service via rest endpoint with only web.config changes, the gate keeper WCF framework didn't invoke the service. Instead it wrote the below details in the svclog file.


"The message with To 'http://localhost/WcfService/Service.svc/rest/GetData?value=2' cannot be processed at the receiver, due to an AddressFilter mismatch at the EndpointDispatcher.  Check that the sender and receiver's EndpointAddresses agree."

The developers understood that they missed end point behavior configuration for the new webHttp end point added to the service. They added end point behavior as below and used this in webHttpEndPoint.

<endpointBehaviors>
        <behavior name="restBehavior">
          <webHttp />
        </behavior>
</endpointBehaviors>

After this change they tried to call the service via ReST url. But this time they got another error in the browser.

405 Method Not Allowed

There was no entries in the svclog file. The developers realized that, there is no way to expose a service via ReST using webHttpBinding without a contract change. They did that contract change and compiled the assembly and put into bin folder.

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet]
    string GetData(int value);
}

After that they called the service using direct url and they got the result. Everybody became happy that the service worked. The result was as follows for the URL

<string xmlns="http://schemas.microsoft.com/2003/10/Serialization/">You entered: 2</string>

But there was one more question. How to use this in browser application where the language is Javascript? If its in JSON, Javascript knows how to process it. They modified the contract again as follows to get in JSON.

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    string GetData(int value);
}

Calling from Javascript

Once they were able to call the ReST url directly from the browser, they used the same url to call from the Javascript code written inside HTML application.


<script type="text/javascript">
    var baseUrl = "http://localhost/WcfService1/Service.svc/rest";
    function testWCFReSTCall() {
        var urlToServiceMethod = getUrlToGetDataMethod();
        
        var xhr = new XMLHttpRequest();
        xhr.open("Get", urlToServiceMethod, false);
        xhr.send();
        if (xhr.status === 200) {
            alert("200" + xhr.responseText);
        }
        else {
            alert("Error on XMLHttpRequest: " + xhr.status + " " + xhr.statusText);
        }
    }
    function getUrlToGetDataMethod() {
        var urlToGetData = baseUrl + "/GetData";
        var urlToGetDataWithParameters = urlToGetData + "?value=2";
        return urlToGetDataWithParameters;
    }
</script>

Tuesday, March 10, 2015

Using ref parameters in WCF service contract

Actually it didn't make sense to have ref parameter in service calls as most of the cases service runs in different process and client don't get reference to the server memory address. But still WCF supports it.

I never thought it will work until I saw this in one of the production applications. We were re-factoring a legacy code base and could see one operation contract with ref keyword. Initially we thought that service itself is not in use and can delete it. But my colleague was sure that it works. So decided to do a sample as running the app and finding out which functionality in that giant app is going to use it takes more time. Below is the PoC we did.

WCF Service contract

Created service contract with 3 operation contracts

    [ServiceContract]
public interface IMathServiceWithRef
{
    [OperationContract]
    int GetSum(int number1, int number2);
    [OperationContract]
    Result GetSumAndAverageAsResultObject(int number1, int number2);
    [OperationContract]
    int GetSumAndAverage(int number1, int number2, ref int average);
}
[DataContract]
public class Result
{
    [DataMember]
    public int Sum { get; set; }
    [DataMember]
    public int Average{ get; set; }
}

WCF Service Implementation

Simple implementation as below

public class MathServiceWithRef : IMathServiceWithRef        
{
    int IMathServiceWithRef.GetSum(int number1, int number2)
    {
        return number1 + number2;
    }
    Result IMathServiceWithRef.GetSumAndAverageAsResultObject(int number1, int number2)
    {
        return new Result() { Sum = number1 + number2, Average = (number1 + number2) / 2 };
    }
    int IMathServiceWithRef.GetSumAndAverage(int number1, int number2,ref int average)
    {
        average = (number1 + number2) / 2;
        return number1 + number2;
    }
}

WCF Client proxy & Test class

Right clicked on the service reference section and added using the svc url. Used simple test project which already have service reference

        [TestMethod()]
public void WithNormalValues_ShouldSuccess()
{
    WCFService1.MathServiceWithRefClient client = new WCFService1.MathServiceWithRefClient();
    int average=0,sum = 0;
    //////////////////////////////////////////
    sum = client.GetSum(20, 10);
    Assert.IsTrue(sum == 30);
    //////////////////////////////////////////
    Result result = client.GetSumAndAverageAsResultObject(20, 10);
    Assert.IsTrue(result.Average == 15 && result.Sum == 30);
    /////////////////////////////////////////
    sum=client.GetSumAndAverage(20, 10, ref average);
    Assert.IsTrue(average == 15 && sum==30);            
}

And this worked as expected. Fiddler results below

Fiddler results

Simple Sum() call

Request XML
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <GetSum xmlns="http://tempuri.org/">
      <number1>20</number1>
      <number2>10</number2>
    </GetSum>
  </s:Body>
</s:Envelope>
Response XML
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <GetSumResponse xmlns="http://tempuri.org/">
      <GetSumResult>30</GetSumResult>
    </GetSumResponse>
  </s:Body>
</s:Envelope>

With ref keyword

Request XML
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <GetSumAndAverage xmlns="http://tempuri.org/">
      <number1>20</number1>
      <number2>10</number2>
      <average>0</average>
    </GetSumAndAverage>
  </s:Body>
</s:Envelope>
ResponseXML
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
      <GetSumAndAverageResponse xmlns="http://tempuri.org/">
        <GetSumAndAverageResult>30</GetSumAndAverageResult>
        <average>15</average>
      </GetSumAndAverageResponse>
    </s:Body>
  </s:Envelope>

As we can see in the fiddler the response xml just contains the ref value. But not as result. 

WCF communication protocols tested

Obviously there is no need to test using various protocols as WCF is more towards protocol independent in all most all the cases.

Still we tested in net.pipe and net.tcp protocols and it worked.

Why someone should use ref keyword in WCF operation contact

If someone is really lazy to create a DataContract class they can use this method. I don't see any other benefits.

Happy coding. 

Tuesday, February 10, 2015

WCF DataServices - Date Time comparison in OData query

The concept of WCF data service which uses OData is really great. But I doubt whether that is ready to be used in an enterprise production applications. The main reason is its immaturity and lack of support on some Linq queries and operators. One of the major item is lack of joins. I believe OData specification itself doesn't have join. Below is another scenario which is not supported by WCF Data Services.

Requirement - Compare date in database against current date

Lets take and scenario where a MessageProcessAttempt table is exposed via WCF Data service. There is a field called DequeuedTime which tells when a message is dequeued. We need to list down all the messages which dequeued in last 1 hour.

In normal sense we can obtain the list by subtracting the de-queued time from current time and checking if the difference < 1 hour. The query can be as follows.

List<MessageProcessingAttempt> msgs = (from msg
                           in qProxy.MessageProcessingAttempts
                           where (DateTime.UtcNow- msg.DequeuedTime.Value).TotalHours<1
                           select msg).ToList();

But it will fail with below error message
"No property 'TotalHours' exists in type 'Edm.DateTime' at position 56."
Position will change based on the code.There will be no compile time errors. It just fails at runtime. Tried to find the details about Edm.DateTime class in msdn but able to find out except one EdmDateTimeConstant class.So what can we do

Solution - Calculate target date and compare

Find the target date and do comparison rather than finding the difference in the OData query.


DateTime timeToFilter = DateTime.UtcNow.Subtract(TimeSpan.FromHours(1));
List<MessageProcessingAttempt> msgs = (from msg
                           in qProxy.MessageProcessingAttempts
                           where msg.DequeuedTime.Value >= timeToFilter
                           select msg).ToList();

Here the major difference we can notice that the date subtraction is not happening via operator and its not producing the TimeSpan obejct. We can have DateTime.UtcNow.Subtract(TimeSpan.FromHours(1)) in OData as well instead of variable and it will work. This points to the fact that TotalHours property is not there in a special type called Edm.TotalHours which is produced as part of subtraction operator.

This was found by our development team in India and I didn't agree to them in the beginning. I spend around 2-3 hours and could see WCF Data Service is still not suitable for enterprise apps. Thanks to the team for finding the workaround.

Happy coding...

Tuesday, January 20, 2015

Debugging exception in WCF IsOneWay=True WCF Services

Recently I had to work on an one way WCF service. The scenario is little different than normal service hosting. There are many services hosted in a server machine using IIS WAS hosting.All of those expose same contact interface. The URLs are obviously different but they follow certain convention such as

net.pipe://localhost/{feature name}/service.svc

The caller has some logic to prepare the above url and it simply calls the service. It uses fire and forget method by decorating contract with IsOneway=True. Below is a similar contract.


[OperationContract(IsOneWay = true)]
void InvokeAsync(Dictionary<string, object> messageInfoDictionary);

After setting up the environment, we started facing one issue. The service implementation is not getting executed. But there is no exception in caller side. In a normal scenario we immediately go to the svclog file, if there is an exception. As there was no exception, the investigation didn't turn into svclogs in the first round.

Analyzed each and every bit of caller code where the url is prepared. No problem at all. Checked the contract methods again and again for any mismatch. Its all perfect. Finally decided to turn on the svclogs in caller side on the assumption that client is not able to establish communication with server.

It shows that there is timeout. But it didn't help to identify the root cause. Then enabled server side svclogs and it helped.

The exception was System.ServiceModel.Dispatcher.NetDispatcherFaultException .It has an inner exception as well which is of type System.Runtime.Serialization.SerializationException. The error message was

"Element 'http://schemas.microsoft.com/2003/10/Serialization/Arrays:Value' contains data from a type that maps to the name 
'http://schemas.datacontract.org/2004/07/{Namespace}:Message'. The deserializer has no knowledge of any type that maps to this name. Consider using a DataContractResolver or add the type corresponding to 'Message' to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding it to the list of known types passed to DataContractSerializer."

Yes its clear the data contract class is in different assembly and that assembly is not available in the bin folder of service. Putting the dll in place fixed the issue.

I am more researching on how these kind of issues can be caught in our code and log properly. This is important as the services which are exposing the same contract are going to be developed by different  and disconnected teams.

Tuesday, September 16, 2014

Overriding without virtual and override keywords in .Net

This is about a particular scenario where we can achieve overriding without virtual or override keywords in C#. Below is the scenario of an inheritance hierarchy.
Here we can see that both the base and derived class implemented the IDisposable interface. In this case we don't need to mention the keyword overrides but the Dispose() of DerivedDisposable class will be called when we invoke the Dispose() method on the IDisposable type variable, if it contains the DerivedDisposable class object.

            IDisposable id = new DerivedDisposable();
            id.Dispose();

This will invoke the method written inside the DerivedDisposable class.

Calling base class Dispose method

Normally in overriding scenarios, we may call the base class implementation by using base.OverriddenMethodName(). But in this case, base object will not have the Dispose method, if the IDisposable is implemented explicitly. Means the code below won't compile.


    class DerivedDisposable : Disposable,IDisposable
    {
        void IDisposable.Dispose()
        {
            base.Dispose();//This wont compile if the base class / class Derived in this example implements the IDisposable explicitly
        }
    }


Next idea what we can do is to cast the base to IDisposable and call the Dispose method. But that too won't compile.


    class DerivedDisposable : Disposable,IDisposable
    {
        void IDisposable.Dispose()
        {
            //DoWork();
            (base as IDisposable).Dispose();//Won't compile
        }
    }

Implicit interface implementation

Only way to call the base class Dispose method is to make sure the base implements the interface implicitly.Then we can call base.Dispose method().


    class Disposable : IDisposable
    {
        public void Dispose()
        {
            Console.WriteLine("Disposable.Dispose");
        }
    }
    class DerivedDisposable : Disposable,IDisposable
    {
        void IDisposable.Dispose()
        {
            //DoWork();
            base.Dispose();
        }
    }


If we are concerned about having additional public function, another workaround is to have separate protected function in base class (eg:DisposeWorker) which is called from the Dispose() of base class to carry out the task. So from the derived class.Dispose() method we can call that protected function.


    class Disposable : IDisposable
    {
        void IDisposable.Dispose()
        {
            DisposeWorker();
        }
        protected void DisposeWorker()
        {
            Console.WriteLine("Disposable.Dispose");
        }
    }
    class DerivedDisposable : Disposable,IDisposable
    {
        void IDisposable.Dispose()
        {
            //DoWork();
            base.DisposeWorker();
        }
    }

Real scenario - Overriding the ClientBase<TChannel>.Dispose

This is useful when overriding the Dispose method of ClientBase<TChannel> class related to WCF to have our own behavior when disposing. In our project as I mentioned in earlier posts, we are not adding service reference to call WCF service. Instead we create our own proxy class by implementing ClientBase<TChannel>. We have proxy pooling technique built into the system and it needs "return  of proxy to the pool" when Dispose is called on proxy object.


    class Client : ClientBase<IService1>, IService1, IDisposable
    {
        void IDisposable.Dispose()
        {
            Console.WriteLine("Disposable.Dispose");
        }
 
        string IService1.GetData(int value)
        {
            throw new NotImplementedException();
        }
    }


I am really not sure whether its overriding or 'feels like' overriding. Anyway I am open to discussions. This is one of the scenario I could see which can only be solved by using implicit interface implementation.We will face this same issue if we implement interfaces explicitly in VB.Net.

Happy coding

Tuesday, September 9, 2014

Why WCF Service cannot be activated when calling from client side?

Last week I came to see one interesting issue related to WPF calling WCF services. One of my colleague asked me to look into his machine as he is not able to call WCF service from WPF application. When I looked into the issue, I could see that the error message at client side is 

The requested service, 'http://<host>/<Service>.svc' could not be activated. See the server's diagnostic trace logs for more information

Diagnose step 1

When ever we see this exception we could understand that the service instance creation got error. If we browse the service url, it internally creates the service object and fail with more error details. So the next step was to browse the WCF service in browser by right click on IIS and browse or give the URL directly, if its known.

That turned out to be more informative

Could not load file or assembly '<assembly name>' or one of its dependencies. An attempt was made to load a program with an incorrect format

If we are not seeing the details we can enable the exception flag.

<serviceDebug includeExceptionDetailInFaults="true"/>

Diagnose step 2

Reset IIS and clear the temporary Asp.Net files. Sometime the temporary Asp.net files will be holding a wring dll.

Location of temporary ASP.Net files for 64 bit .Net 4.0 applications is - %Windir%\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files

Location of temporary ASP.Net files for 32 bit .Net 4.0 applications is - %Windir%\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files

Tried this step but no luck.

Diagnose step 3

This leads to the situation where one assembly file present in the bin folder is not getting loaded due to some exception. There are chances that it depends on another dll and that is causing issue. Also chances are that it might be loading the dll from some other location such as GAC. 

So better idea is to see the assembly binding fusion log using the fuslogvw tool .Tried that and got more detail. Basically enabled the registry key, then we can see the fusion log in the browser itself. It says

===
LOG: This bind starts in default load context.
LOG: Using application configuration file: D:\TFS\TestDotNet\WcfService1\web.config
LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework64\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/wcfservice1/63540997/f07fffe5/ClassLibrary20.DLL.
LOG: Attempting download of new URL file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/Temporary ASP.NET Files/wcfservice1/63540997/f07fffe5/ClassLibrary20/ClassLibrary20.DLL.
LOG: Attempting download of new URL file:///D:/TFS/TestDotNet/WcfService1/bin/ClassLibrary20.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated

This means the dll is loaded from proper location. So need to go next step.

Diagnose step 4

Need to have closer look at the exceptions and their call stack to understand how far its reaching and where its failing. The exception call stack is given below which was present in the browser when service is browsed.


[BadImageFormatException: Could not load file or assembly '<assembly name>' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +210
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +242
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +17
   System.Reflection.Assembly.Load(String assemblyString) +35
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +122

[ConfigurationErrorsException: Could not load file or assembly '<assembly name>' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +12761078
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +503
   System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +142
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +334
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +203
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +152
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +1151

[HttpException (0x80004005): Could not load file or assembly '<assembly name>' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12881540
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12722601


There were 3 exception one after another. Configuration exception and HttpExceptions are the outer ones and the real problem is stated in the very inner exception which is nothing but BadImageException.

BadImageException usually happens when we try to load 32 bit assembly in 64-bit applications or when the assembly is corrupted. 

Diagnose step 5

We can check whether the assembly is corrupted by opening it in reflector or any other decompilation software. If reflector is able to load the dll, there is no issue. In this case, I was able to open the file in reflector.

Diagnose step 6

Next we need to make sure all the assemblies are marked as 64 bit / AnyCPU when compiled. The ASP.Net hosting mechanism loads all the dlls when its started. Based on the application pool setting "Enable 32-Bit Applications" flag, it decide the processor architecture of web application. If there is any dll which is not matching with bit size, it will throw this bad image exception. We could see that the assembly which was causing, is built using x86 mode where the app pool is exclusive for 64bit applications.

Recompiled using 'AnyCPU' setting. Reset IIS and cleared the Temporary ASP.Net Files. Everything worked.

Tuesday, September 2, 2014

Hosting WCF service in IIS and System.Web.WebPages.Deployment

As per MSDN the System.Web.WebPages,Deployment namespace contains "the classes that are used to confirm the deployment of web applications". It make sense for web applications which contains web pages created using .aspx or Razor. But what is the relation between this System.Web.WebPages.Deployment.dll and WCF service application which hosted inside IIS which is exposed via netNamedPipes ?

As we have seem in my previous post about SSMS and System.Transactions.dll, I got a machine crash and the machine started behaving in its's own way which resulted in problems. Now when I host WCF services inside IIS there are problems. The services, I was able to browse before the crash stopped working with below error message.

Could not load file or assembly 'System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The module was expected to contain an assembly manifest

The call stack looks as follows

[BadImageFormatException: Could not load file or assembly 'System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The module was expected to contain an assembly manifest.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +34
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +16
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The module was expected to contain an assembly manifest.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +752
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +57
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +91
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +258
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +135
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516

[HttpException (0x80004005): Could not load file or assembly 'System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The module was expected to contain an assembly manifest.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873912
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254


One possibility for BadImageFormatException is the mismatch of runtime. ie if we try to load x86 assembly in x64 application or other way we may get this exception. I tried enabling 32 bit support in the application pool by setting the "Enable 32-Bit Applications" flag in IIS. 

It did't help.

Then looked at all the config files possible such as aspnet.config and machine.config. Nowhere I was able to find any entry to the problematic dll. Then I decided to find out the assembly binding information which is as follows

=== Pre-bind state information ===
LOG: User = NT AUTHORITY\NETWORK SERVICE
LOG: DisplayName = System.Web.WebPages.Deployment, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
 (Fully-specified)
LOG: Appbase = file:///<drive>:/TFS/TestDotNet/WcfService1/
LOG: Initial PrivatePath = <drive>:\TFS\TestDotNet\WcfService1\bin
Calling assembly : (Unknown).
===


Here its clear that the calling assembly is unknown which I assume any framework dll. May be it was earlier getting loaded from GAC and after the crash GAC registration might be broken. So I figured out the location of he dll and registered into GAC.

Location of System.Web.WebPages.Deployment.dll - <Install drive>:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v2.0\Assemblies

But the GACUtil failed with a message as follows.

The module 'System.Web.WebPages.Deployment.dll' was expected to contain an assembly manifest.

Then I tried open the dll in reflector and could see that, it was not able to open as its no more a .net dll and it displayed more detailed error message


File is not a portable executable. DOS header does not contain 'MZ' signature.


This leads to a conclusion that the System.Web.Webpages.Deployment.dll is corrupt. So next option is repair or re-install. So went to appwiz.cpl and re-installed "Microsoft ASP,Net Webpages 2".

It worked!!!

But why WCF hosted in IIS needs System.Web.WebPages.Deployment.dll which is for web page related :-(