Sunday 13 January 2013

Could not find the conceptual model type

I have been playing around recently with ASP .Net MVC, and after adding new tables to the Entity Framework model of my test app I started getting the following error:

"Could not find the conceptual model type"

After getting mad for a while I found the solution. For what I read around the web there is a bug with EF that causes problems when the .edmx file is in the same project as your models.

I moved the Entity Framework model to a separate new project in my solution and everything worked fine from there.

Wednesday 11 July 2012

Current cannot be set directly when Com+ Interop is enabled.

Every now and then I found one obscure error which there is no way of finding in the internet anyone with the same problem. Or at least any english speaker.

When you google for it you just found five results, and usually they are in a mix of Russian, Korean, Hebrew... so you don't have a clue what is going on anyway.

This is the first post of a tag I will call "Russian Result", where I will share with you those errors I found and how I fixed them. Most of them are the typical errors you don't get when starting a new project, but those you found when you are maintaining an existing system.

Today we will cover the following error: "Current cannot be set directly when Com+ Interop is enabled."

 This error appeared when we make one of our webservices, running in a machine dedicated for them, to start a transaction that should be resued by the business logic layer which is accessed through COM+. The reason for that new transaction was to make two separate calls to the BLL share the same transaction.

In order to make it work we needed to change the way the BLL inititates the TransactionScope so it does it with Interop support, so the transaction can be enlisted in the Transaction shared by COM+.

After changing the appropriate methods everything went ok, until one day the error was thrown by another piece of code that used the Full Interop transactions.

The piece of code failing looked like this:


Transaction currentTran = Transaction.Current;
DependentTransaction depTran;
depTran = currentTran.DependentClone(DependentCloneOption.BlockCommitUntilComplete);
parameters._currentTransaction = depTran;
PopulateObjectThread(a);
// PopulateObjectThread code

CustomParameters a = stateInfo as CustomParameters;
DependentTransaction dependentTransaction;
dependentTransaction = a._currentTransaction as DependentTransaction;

Transaction oldTransaction = Transaction.Current;
try
{
      Transaction.Current = dependentTransaction;
      // DO WORK 
      dependentTransaction.Complete();
}

As you can see the original method being called "PopulateObjectThread" used to be a Thread body but that is no longer the case.

In order to share the transaction with the main thread a Dependant Transaction was created and assigned in the thread body. This was the exact action that was causing the error. Assigning the current transaction when COM+ Interop is enabled.

In our code it didn't make sense to do that anymore as we don't use threads so we just removed that bit of code. Other option would have been to move the code to a Thread and keep the code as it is, which also seem to work.

So if you find this error think that the reason is:
- You have a transaction with full interop enabled
- You are trying to change the current transaction in the thread that has initiated the full interop transaction

So you know what to do.

Hope this is of help to someone. With some luck next guy googling for this error will find something he can read, please leave a comment so I know of your luck!

Sunday 8 July 2012

Memory leak actualizando Enterprise Library de la version 3.1 a 5.0


The english version of this article can be found HERE.


Recientemente he estado trabajando en la actualización de un proyecto de .Net 3.5 a .Net 4, y de paso hemos actualizado de usar la Enterprise Library de la versión 3.1 a 5.0 y empezar a utilizar Unity para la inyección de dependencias ya que no hay bloque para ello en la nueva entlib.

Durante la actualización tuve que aplicar algunos de nuestros cambios a medida a la librería, principalmente a los bloques de Caching y Data, sin muchos problemas ya que el código que necesitaba los cambios sigue siendo bastante similar.

Pero una vez comencé a probar la aplicación me di cuenta de que habiamos introducido un enorme Memory Leak. En principio no era obvió que es lo que estaba ocurriendo hasta que encontre una forma de reproducirlo consistentemente.

Using the profiler of my choice (YourKitProfiler, very nice tool indeed!) I found out that there were a nice leak of Unity objects. Monitoring were those objects were being created I ended up in the method we used to get a new database connection.

Empleando mi profiler preferido (YourKitProfiler, que es una herramienta bastante salada) encontré que el leak principal era de objetos Unity. Monitorizando donde se creaban esos objetos acabé llegando al método que empleamos para solicitar una nueva conexión a base de datos.

DatabaseProviderFactory factory = new DatabaseProviderFactory();  
SqlDatabase db = factory.CreateDefault() as SqlDatabase;  

Como puede verse nuestro uso de las "Provider Factories" no era el apropiado ya que no haciamos Dispose de los objetos una vez habiamos terminado con ellos y creabamos una nueva instancia cada vez que necesitábamos una conexión a base de datos.

Lo curioso es que el uso de Unity por parte de la nueva versión de la Enterprise Library esta produciendo un grafo de dependencias entre objetos más complejo del que se creataba hasta entonces, por lo que pese a que antes no existía el Leak ahora si no haces Dispose como se debe el Garbage Collector no es capaz de limpiar los objetos.

Arreglé el problema empleando una instancia estática del Provider, de forma que siempre usamos el mismo objeto cada vez que necesitamos la conexión de base de datos. Otra opción habría sido usar un bloque "Using" para ese trozo de código, pero ya es cuestión de cada uno.

Imagino que un problema similar se encontraría de usar de la misma forma cualquiera de los otros Provider Factories de la Enterprise Library, no solo con la de bases de datos. así que si encontráis cualquier memory leak en vuestra aplicación tras actualizar de la versión 3.1 aseguraros de que estais usándolos correctamente.

Actualizacion: parece que hacer dispose de tus providers no funciona. Cada vez que creas una instancia de uno el fichero de configuracion es procesado por Unity, creando un grafo de objetos que lo representa y que no parece que se "dispose" incluso cuando haces dispose del provider. Asi que intenta mantener el número de providers al mínimo necesario, usando por ejemplo singletons.

Wednesday 23 May 2012

Memory leak upgrading Enterprise Library from 3.1 to 5.0

La versión en castellano de este artículo puede encontrarse AQUÍ

I have been working recently in upgrade a project from .Net 3.5 to .Net 4 and in the way I have upgrade the Enterprise Library from version 3.1 to 5.0 and started using Unity, as it is no longer part of the entlib.

During the upgrade I did some of our tailored changes to the library, mainly the Data and Caching blocks, without much problems, as the code is still quite similar in the areas that required changes.

But once I started to test the application I noticed a big memory leak on it. Initially it wasn't obvious by I managed to work out a way to reproduce it consistently.

Using the profiler of my choice (YourKitProfiler, very nice tool indeed!) I found out that there were a nice leak of Unity objects. Monitoring were those objects were being created I ended up in the method we used to get a new database connection.

DatabaseProviderFactory factory = new DatabaseProviderFactory();  
SqlDatabase db = factory.CreateDefault() as SqlDatabase;  

Our usage of the Provider Factories wasn't the proper one as we weren't disposing them and we were creating a new instance each time we needed a database connection.

Looks like the usage of Unity as part of the enterprise library started to create a complex graph of objects each time you instantiate one of the factories, so if you don't dispose them properly the GC is not able to remove them.

I fixed the problem by using an static instance of the provider, so I use always the same object each time I need a database connection. Another option would have been wrapping that piece of code inside an using block, but it is up to you.

I assume a similar problem is present if you use of any of the Provider Factories in the Enteprise Library, not only on the Database one, so if you find that you have a memory leak in your application after upgrading from version 3.1, have a look at the way you use them.

Update: looks like disposing your providers doesn't work. Each time you create an instance of one of them the configuration file is parsed and an object graph representing it  is created by Unity, which seems its not disposed even if you dispose the provider. So try to reduce the number of providers you create to a minimun, using a singleton for example could be a good idea.

Otro blog de programación



El desarrollo software es una de mis pasiones, compartida con las que trata mi otro blog, y muchas, muchísimas más.

Pero hacer software es una de las cosas de las que va mi vida. Llevo trabajando en desarrollo unos cuantos años, comencé en el mundo de Java y fui saltando de una cosa a otra, hasta que finalmente he terminado como un programador .Net, y no tiene pinta de que sea algo que vaya a cambiar en el futuro cercano.

Disfruto compartiendo los problemas que dan dolores de cabeza durante horas, dias o incluso semanas y finalmente consigo solucionar. Los comparto con mis compañeros y otros amigos programadores, pero creo que sería capaz de compartirlo con unos cuantos más a través de este blog.

Aunque el lenguaje principal (en el que primero aparecerás las entradas) es el Inglés, trataré de poner traducciones de cada entrada en castellano, ya que me da la impresión de que no son muchos los blogs en nuestra lengua que hay por ahí sobre .Net, y supongo que habrá quien los preferirá aunque tampoco que nadie de nuestro gremio tenga demasiados problemas para seguirlos en ingles.

Y eso es prácticamente todo. Tan solo otro programador "friki" que quiere compartir las que cosas en las que pasa las horas con otros programadores "frikis", y quizás ayudarles en el proceso.

Perdonadme si no actualizo el blog muy a menudo, pero como os he dicho tengo demasiadas "pasiones" ;)

Another coding blog

Computer science and software development are two of my passions, shared with the ones my other blog is about and many, many others.

But developing software is one of the things my life is about. I have been working in development for a few years now, started in the Java world and move through different things, and finally I have end up as a .Net developer. And it doesn't seem its going to change in the near future.

I love to share those problems I have been struggling to fix for hours, days, or even weeks, and finally I manage to deal with. I do share them with my team mates, with my other coder friends, but I think I am going to be able to manage sharing it with some more people via this blog.

Although the primary language of the blog is going to be English, I will try to post translations of every entry in Spanish, my mother tongue, as I think there are not many blogs out there in Cervante's language about .Net... if there are I would be glad to see them!

So basically that is it. Just another geeky coder that wants to share the thing he spent the hours on with other geeky coders, and maybe help some of then in the way.

Forgive me if I don't update the blog much often, but I have to many passions ;)