I’ve already blogged in the past on how to easily troubleshoot WCF Exception and that suggestion is valid for every exception you encounter in WCF. Today I have a function that gave the error
System.ServiceModel.CommunicationException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. —> System.Net.WebException: The underlying connection was closed: A connection that was expected to be kept alive was closed by the server. —> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. —> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
This problem is usually caused by some error in the communication channel, but even in such a situation, enabling the trace listener immediately gave to you an idea of the problem.
Figure 1: How to identify the problem thanks to WCF Trace Listener
In my situation the error is ClientProxy …. is not expected and this is due to the fact that I’m returning from WCF a couple of classes that are mapped with NHIbernate, the entity returned has a property of type Customer that is a lazy property, thus at runtime it is represented by a dynamic proxy that is not known to WCF. The solution is trivial, just issue a Fetch(obj => obj.Client) in the LINQ query to fetch Client and avoiding NH to create a proxy, but the key point is that with WCF trace listener, finding problems in WCF is matter of few seconds.
Gian MAria.
Tags: Nhibernate, Wcf
No commentsI’ve blogged some time ago that I’m starting to consider ORM an Antipattern, and recently Mr Fowler posted similar thoughts in his bliki, moreover I have the pleasure to be one of the organizer of the first RavenDB official Course in Italy, with my dear friend Mauro as teacher.
Since I’m strongly convinced that in a full OOP approach to problem objects should not have nor setter nor getter, most of the work and complexities of an ORM is simply not needed, because you usually retrieve objects from the storage with only one function GetById and nothing else. In my long experience with NHibernate, I verified that most of the problem arise when you need to show data in UI in specific format and you start to write complex Query in HQL or ICRiteria or LINQ, then you need to spend time with NHProfiler to understand if the queries are good enough to run on production system and when objects changes a little bit you need to rewrite a lot of code to suite the new Object Model. This last point is the real pain point in DDD, where you usually should create Object Model that will be manipulated a lot before reaching a good point, after all the main value of DDD approach is being able to create a dialog with a DOMAIN EXPERT and it is impossible to find a good Object Models at the first tentative. If refactoring a model become painful, you are not allowed to modify it with easy, you are going away from DDD approach.
This is where CQRS can help you, for all objects belonging to the domain you need only to Save, LoadById, Update and delete, because every read model should be defined somewhere else. In such a scenario an ORM is really useful, because if you need to store objects inside Relational Database you can leave the ORM all the work to satisfy the CRUD part, where the R is the method GetById. To start easily with this approach you can create SQL View or stored procedures for all the Read Models you need; this imply that whenever the structure of the Domain Model changes, you need only to change all affected Read Models, some view and some stored procedure, but you have no need to refactor the code.
In this situation the ORM can really helps you, because if you change the Domain Model, you should only change the mapping, or let some Mapping by convention do this for you (ConfORM for NH is an example), regenerate the database and update only affected Read Models. If your domain is really anemic, if you expose properties from objects, even only with getters, whenever you change a domain class you should answer the question “If I change this property, what other domain objects will be affected? How many service class will be affected? How many query issued from Views will be affected?”. If you are not able to create a Read Model with SQL View or stored procedure, you can write a denormalizer that listens for DOMAIN EVENTS and populate the Read Model accordingly. In my opinion this is the scenario where an ORM can really helps you.
In such a situation a NoSql database can dramatically simplify your life, because you do not need an ORM anymore, cause you are able to save object graps into the storage directly, and you can create Read Models with Map/Reduce or with denormalizers.
But sadly enough, ORM are primarily used to avoid writing SQL and persist completely anemic domain, where all the logic reside on services. In such a scenario it is easy to abuse an ORM and probably in the long term the ORM could become much more a pain than a real help.
Gian Maria.
I’ve dealt in a previous post with the new Shim library in Vs11 that permits you to test “difficult to test code” and I showed a really simple example on how to use Shim to isolate the call to DateTime.Now to simulate passing time in a Unit Test. Now I want to change a little bit the perspective of the test, in the test showed in previous post I simply exercise the sut calling Execute() a couple of time, simulating the time that pass between the two calls. Here is the test
[Fact]
public void Verify_do_not_execute_task_if_interval_is_not_elapsed()
{
using (ShimsContext.Create())
{
Int32 callCount = 0;
PerformHeavyTask sut = new PerformHeavyTask(10, () => callCount++);
DateTime startDate = new DateTime(2012, 1, 1, 12, 00, 00);
ShimDateTime.NowGet = () => startDate;
sut.Execute();
ShimDateTime.NowGet = () => startDate.AddMinutes(9);
sut.Execute();
Assert.Equal(1, callCount);
}
}
I can also change the point of view and write a test that uses a shim to isolate the SUT, this is a less common scenario but it can be also really interesting, because it shows you how you can write simple White box Unit Tests isolating part of the SUT. The term White Box is used because this kind of Unit Test are created with a full knowledge of the internal structure of the SUT, in my situation I have a private method called CanExecute() that return true/false based on the interval of time passed from the last execution and since it is private it makes difficult for me to test the SUT.
private Boolean CanExecute() {
return DateTime.Now.Subtract(lastExecutionTime)
.TotalMinutes >= intervalInMinutes;
}
But I can create a Shime on the SUT and isolate calls to the CanExecute(), making it return the value I need for the test, here is an example
[Fact]
public void Verify_can_execute_is_honored()
{
using (ShimsContext.Create())
{
Int32 callCount = 0;
PerformHeavyTask sut = new PerformHeavyTask(10, () => callCount++);
ShimPerformHeavyTask shimSut = new ShimPerformHeavyTask(sut);
shimSut.InstanceBehavior = ShimBehaviors.Fallthrough;
shimSut.CanExecute = () => false;
sut.Execute();
Assert.Equal(0, callCount);
}
}
To write this test I’ve added another fake assembly on the assembly that contains the PerformHeavyTask class to create shim for the SUT. This test basically create a ShimPerformHeavyTask (a shim of my SUT) passing an existing instance to the SUT to the constructor of the shim, then I set the InstanceBehavior to ShimBehaviors.Fallthrough to indicate to the Shim Library to call original SUT method if the method was not isolated. At this point I can simply isolate the call to the CanExecute() private and non-virtual method, specifying to the shim to return the value false, then I call the Execute() method and verify that the heavy task is not executed.
This test shows how to create a shim of the SUT to isolate calls to its private methods, thanks to the Fallthrough behavior; if you forget to change the InstanceBehavior the test will fail with an exception of type ShimNotImplementedException, because the default behavior for a Shim is to throw an exception for any method that is not intercepted. Thanks to shim library you can simply isolate every part of the SUT, making easier to write Unit Test for classes written with no TDD and no Unit Testing in mind.
Gian Maria.
- Basic Request Response WCF service
- Reason behind a request – response service in WCF
- Evolving Request Response service to separate contract and business logic
- How to instantiate WCF host class with MEF
One of the problem I had to solve to make WCF and MEF live together, is knowing all the types discovered by MEF at runtime for a given export. This information is really important because I need the list of type that derived from Request and Response to inform WCF of all the KnownTypes available to the service. First of all let’s see how I initialized MEF engine
private static CompositionContainer theContainer;
private static DirectoryCatalog catalog;
static MefHelper()
{
catalog = new DirectoryCatalog(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
theContainer = new CompositionContainer(catalog);
}
The catalog is instructed to load everything that is located in the current directory, a configuration that is suitable for my simple WCF Request / Response service; then I need to change the DynamicKnownType class to get the list of exported types loaded by MEF.
class DynamicKnownType
{
static List<Type> knownTypes;
static DynamicKnownType()
{
knownTypes = new List<Type>();
knownTypes.AddRange(MefHelper.GetExportedTypes<Request>());
knownTypes.AddRange(MefHelper.GetExportedTypes<Response>());
}
The GetExportedType() method is a little tricky, because MEF does not offer such a functionality out of the box, so I need to search inside information available from the catalog to identify all loaded types related to a specific Export. The code is quite simple and it is composed only by few lines.
public static IEnumerable<Type> GetExportedTypes<T>()
{
return catalog.Parts
.Select(part => ComposablePartExportType<T>(part))
.Where(t => t != null);
}
private static Type ComposablePartExportType<T>(ComposablePartDefinition part)
{
if (part.ExportDefinitions.Any(
def => def.Metadata.ContainsKey("ExportTypeIdentity") &&
def.Metadata["ExportTypeIdentity"].Equals(typeof(T).FullName)))
{
return ReflectionModelServices.GetPartType(part).Value;
}
return null;
}
You can find all type related to an export because MEF Catalog contains a property named Parts that is an IEnumerable of ComposablePartDefinition, where each instance contains full details on a type discovered by MEF. For each ComposablePartDefinition I can cycle inside all ExportDefinitions list to find if one ExportDefinition is related to the type I’m looking for. This specific information is not exposed directly, but it is contained in the Metadata associated to the ExportDefinition in a key called “ExportTypeIdentity” that contains the FullName of exported Type.
If one of the ExportDefinition exports the type I’m searching for I can finally use the ReflectionModelService.GetPartType() static method to find the type of dynamically imported class. This simple method make possible to discover the list of all concrete classes loaded by MEF that inherit from Request or Response to create the list of KnownTypes for WCF.
Figure 1: From the Wcf Test Client you can choose between all the requests that were dynamically loaded by MEF
Example can be downloaded here.
Gian Maria.
Tags: Wcf
No comments- Basic Request Response WCF service
- Reason behind a request – response service in WCF
- Evolving Request Response service to separate contract and business logic
I described in the last post of the series the structure behind the Request/Reponse service based on MEF, now it is time to explain how to make MEF and WCF happily live together. In the first version I hosted the service with these simple lines of code
using (ServiceHost host = new ServiceHost(typeof(CoreService)))
{
host.Open();
Basically all I needed to do is to create a ServiceHost specifying in the constructor the type of the class that implements the service and let WCF to take care of every details about the creation of the concrete instances that will answer to the requests.
In this new version of the service the CoreService class cannot be anymore created with default constructor, because I need to construct the instance with MEF; so I need to instruct WCF to create the CoreService class with MEF.
What I need is concrete implementation of the IInstanceProvider, an interface used by WCF to manage the creation of concrete classes that implements my service.
class CoreServiceInstanceProvider : IInstanceProvider
{
public object GetInstance(System.ServiceModel.InstanceContext instanceContext, System.ServiceModel.Channels.Message message)
{
return MefHelper.Create<ICoreService>();
}
public object GetInstance(System.ServiceModel.InstanceContext instanceContext)
{
return GetInstance(instanceContext, null);
}
public void ReleaseInstance(System.ServiceModel.InstanceContext instanceContext, object instance)
{
}
}
My implementation is super simple, I only need to use the MefHelper.Create() method to let MEF create the class and compose everything, but I need another couple of classes to instruct WCF to use my CoreServiceInstanceProvider to instantiate classes for my service. First class is a Service Behavior, represented by a class that implements IServiceBehavior to make WCF use my CoreInstanceProvider, then I create another class that inherits from ServiceHost to automatically add this behavior to the WCF host.
public class CoreServiceBehavior : IServiceBehavior
{
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)
{
ChannelDispatcher cd = cdb as ChannelDispatcher;
if (cd != null)
{
foreach (EndpointDispatcher ed in cd.Endpoints)
{
ed.DispatchRuntime.InstanceProvider = new CoreServiceInstanceProvider();
}
}
}
}
public void AddBindingParameters(ServiceDescription
serviceDescription,
ServiceHostBase serviceHostBase,
Collection<ServiceEndpoint> endpoints,
BindingParameterCollection bindingParameters)
{
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
}
public class CoreServiceHost : ServiceHost {
public CoreServiceHost() : base(typeof(CoreService))
{
}
protected override void OnOpening()
{
Description.Behaviors.Add(new CoreServiceBehavior());
base.OnOpening();
}
}
With these helper classes, hosting the service in a simple console application is a breeze.
using (ServiceHost host = new CoreServiceHost())
{
host.Open();
Et voilà, two lines of code and I’m able to start the service where every instance of the service is created by MEF.
Gian Maria.
Tags: Architecture, Wcf
2 Comments