Enterprise Library ExceptionManager.Current Throws ‘Exception Thrown By Target Of Invocation’ After Renaming Namespace

December 14, 2011

The problem, dear Tadpolers, is that the ExceptionManager cannot load because the type of the Exception no longer exists because the namespace that it originally lived in has just been renamed. Therefore the ExceptionManager cannot load its handlers.

In my case I had a ReplaceHandler:
add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" exceptionMessage="Data Access Error. Please notify Service Desk." exceptionMessageResourceType="" replaceExceptionType="Common.RepositoryException, Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"

But then I renamed The Namespace ‘Common’ to Norbert.Common, so the next time the ExceptionManager tried to load its ReplaceHandler it could not find the namespace Common or the type Common.RepositoryException, so its threw a TargetInvocationException.
I had to go through my app.config and update all instances of Common.RepositoryException to Norbert.RepositoryException like so:

add name="Replace Handler" type="Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.ReplaceHandler, Microsoft.Practices.EnterpriseLibrary.ExceptionHandling, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" exceptionMessage="Data Access Error. Please notify Service Desk." exceptionMessageResourceType="" replaceExceptionType="Norbert.Common.RepositoryException, Common, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"

Sweet As..

Adding existing entity to Association: An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.

November 24, 2011

I got this error when adding a new entry to a Property in my Entity which is a Navigation property.

To get around this you must Detach the entity already in your Context which has the same key as the entity you are trying to add to your Context. The Gotcha is that if you insert an entity into a List which is a Navigation Property then Entity Framework marks that entity as ‘Added’ even though it is not actually New.

As my now dearly beloved Stack Overflow contact, Shimmy, explained

if you set a navigation property to a tracked entity the new entity is automatically added:
Dim s = context.States.FirstOrDefault() Dim a As New Address a.State = s Dim state = a.EntityState ‘= Added

In my case, adding a Zeppelin to a Hanger which contains a list of Zeppelins:

SelectedHanger.Zeppelins.Add(zep); // Throws ‘object with same key…’ exception

The exception is thrown because my ctx.Zeppelins already contained a Zeppelin with Id equal to zep.Id. Same object key, therefore KABOOM. That zep BTW, was not an actual new Zeppelin but a Zeppelin selected from a list of Zeppelins in a DropDown. Even though Selectedhanger.Zeppelins did not contain a Zeppelin with Id = zep.Id, the fact that I had added zep to SelectedHanger.Zeppelin caused EF to initialise the EntityState of zep to ‘Added’ in the Context. Capiche ?

So to successfully add zep to Hanger.Zeppelins:

Zeppelin ctxZep = ctx.Substations.Where(z => z.Id == zep.Id).Single();
ctx.Zeppelins.Detach(ctxZep);
ctx.Zeppelins.Attach(zep);

Noice.

Enity Framework: Unable To Delete Entity Because Primary End Of Foreign Key Constraint Has Been Deleted

November 23, 2011

I got this error even though the Foreign Key constraint had been deleted from the database and I had re-executed all my EF Template files, had refreshed my Model from the database and had deleted the relevant Navigation propertry from my Model.

Thing is , I had forgotten to physically delete the Association in the Model Designer .edmx file. When I did that and then re-ran my Model Template file all was well.

So I reckon I had only refreshed the secondary (referencing) table in the FK side. Next time I will refresh the primary (referenced) table as well.

That’s all. Get back to what you were doing. The door is the wooden thing in the wall behind you.

SelectMany Example: Flatten Parent Child Association Into A Single List

October 28, 2011

I’m starting to get the hang of LINQ SelectMany now.

Here’s a great article which explains SelectMany better than any other I’ve read. For this James Etheredge is awarded the BTWT Golden Tadpole With Anachronistic Zeppelin for services to Brain Improvement.

So the key is to recognise that SelectMany needs a List to work on. Well, not a List exactly. SelectMany actually works on an IEnumerable. But to get started with SelectMany we can take the conceptual shortcut of thinking of SelectMany as working on instances of List.

So if I have a list of Tadpoles each of which contains a list of Zeppelins and I want to flatten that list I just say:

List (Of TadpoleZeppelins) tadZeps = tadpoles.SelectMany(tad =>
CreateTadpoleZeppelin(
tad.Zeppelins.ToList())).ToList();

CreateTadpoleZeppelin creates a list of TadpoleZeppelins out of a List of Zeppelins, like so:

CreateTadpoleZeppelin(List(Of Zeppelin) zeps)
{
List(Of TadpoleZeppelin) tadZeps = new List (Of TadpoleZeppelen)
zeps.ForEach(zep =>
{
TadpoleZeppelin tadZep = new TadpoleZeppelin();
tadZep.NumFins = zep.Tadpole.NumFins;
tadZep.HeliumCapacity = zep.HeliumCapacity;

tadZeps.Add(tadZep);
});

return tadZeps;
}

I think that’s pretty self-explanatory.

Footnote
If the example seems a bit weird just substitute ‘Customer’ for ‘Tadpole’ and ‘Order’ for ‘Zeppelin’

XamComboBox ComboBoxItemsProvider Very Slow In XamDataGrid

October 25, 2011

I had a page which took 10 seconds to load. When I removed the XamDataGrid Column containing my ComboBoxProvider it took less than 2 seconds to load.

The fix to make it faster was to initialize the ComboBoxProvider through a much faster class. Because ComboBoxProvider is being created once per row, the savings were massive. I also threw away some redundant Binding which cut down on processing time for every DataGridRow.

So I changed this:

igEdit:ComboBoxItemsProvider x:Key="SlowOperationTypeProvider"
ItemsSource="{Binding Source={x:Static enum:EnumDictionary.OperationTypeDictionary}}"
DisplayMemberPath="Key" ValuePath="Value"

To This

igEdit:ComboBoxItemsProvider x:Key="FastOperationTypeProvider"
ItemsSource="{Binding Source={x:Static classlib:Defaults.OperationTypes}}"

EnumDictionary uses Reflection to read a .NET DescriptionAttribute which contains a user-friendly Description for my OperationType Enum. SlowComboBoxItemsProvider iterated through the Enum, used Reflection and Object Casting to create its Dictionary, then used Reflection again to perform DataBinding.

FastComboBoxItemsProvider extracted only the Keys (strings) from an already created EnumDictionary and did not require DisplaymMemberPath or ValueMemberPath attributes. Like I say, I saved 8 seconds in a DataGrid containing only 10 rows.

Entity Framework Type FixupCollection`1 is not marked as serializable.

October 21, 2011

Entity Framework Autogenerated Classes Not Marked as Serializable.

This error comes about while trying to Serialize an EntityFramework Entity that has Associations. I got my error after creating a New entity, saving it, then doing Update on the newly created entity.

A workaround is to add the [Serializable] attribute to the FixUpCollection class, which is located in your .cs file. So, if your EF Template is called StudentEnrolment.tt then FixupCollection is located in StudentEnrolment.cs. Make FixupCollection look like this:

[Serializable]
public class FixupCollection : ObservableCollection

The permanent fix is to modify your Entity Framework template file to make sure that every time your template is run and your Entity classes regenerated then the Serializable attribute is plonked on top of the EF FixupCollection class.

So edit your equivalent StudentEnrolments.tt and find the line where FixupCollection is generated and simply insert the text “[Serializable]” above it, exactly as you would in your class definition, like so:


#>
// An System.Collections.ObjectModel.ObservableCollection that raises
// individual item removal notifications on clear and prevents adding duplicates.
[Serializable]
public class FixupCollection : ObservableCollection
{

All credit to marc_s at Stack Overflow who wrote this and Ross Pace who linked to it from here.

Once again for lovers of Stack Dumps, here’s the full error:

Type 'SubstationLoad.Data.Model.FixupCollection`1[[SubstationLoad.Data.Model.Substation, SubstationLoad.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' in Assembly 'SubstationLoad.Data, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.

Adding An Additional Item To A Collection In Entity Framework With Repository Pattern

October 13, 2011

My application has Entities named ‘Hazards’ and ‘Hazard Groups’. A HazardGroup contains many Hazards and the Hazards may be moved from one HazardGroup to another via a Dialog Box.

I found when trying to add an existing Hazard to an existing HazardGroup that I was getting (to paraphrase) ‘Cannot create association: Objects were created in different Data Contexts’ error message. So I needed to put the Hazard and the HazardGroup in the same Object Context.

Here’s how I ended up doing it:

using (var ctx = new HazardContext())
{ {
Hazard movedHazard = _moved hazard returned from my Dialog Box_;
ctx.HazardGroups.Attach(SelectedHazardGroup);
ctx.Hazards.Attach(movedHazard);
SelectedHazardGroup.Hazards.Add(movedHazard);
}

Just to make it spicier I was also using the Repository Pattern, so I had to make sure that my SelectedHazardGroup was attached to the active Repository, like so:

using (var ctx = new HazardContext())
{
IRepository (Of HazardGroup) repo =
new Repository (Of HazardGroup)(ctx);

repo.Attach(SelectedHazardGroup);
Hazard movedHazard = _moved hazard returned from my Dialog Box_;
ctx.Substations.Attach(movedHazard);
SelectedHazardGroup.Hazards.Add(movedHazard);
repo.SaveChanges()
}

HTH.

System.Configuration.ConfigurationErrorsException The Process Was Terminated Due To An Unhandled Exception.

September 26, 2011

We were getting these error in our UAT environment, but not DEV. Betcha you are too.

The reason for this error is that your Config file does not have the structure expected by the .NET runtime. This means that the app. crashes when the Configuration File is accessed.

The particular way in which our config file was malformed was that we were missing the Oracle.DataAccess.Client Section within system.data which was expected because the runtime was trying to load that section due to the presence of a DbProviderConfigurationHandler.

That DbProviderConfigurationHandler was being invoked because we are using Entity Framework connecting to an Oracle Database. EntityFramework was attempting to load various Oracle bits and pieces because the connection string in the app.config within the Visual Studio Class Library Project that connected to the database (i.e. our DAO project) was attempting to load the Oracle DataAccess Provider. This invoked the DbProviderConfigurationHandler but the relevant section in the app.config was not present.

Later on when we manually added the Oracle.DataAccess.Client section we got a crash because the tester’s machine did not have a full installation of Oracle Client for Entity Framework. That’s this sucker.

Now, solving this this was an enormous relief to us because that MinDate setting was being used to dynamically populate an Infragistics ValueConstraint control. When app.config was accessed that control would throw a humungous StaticMarkup Exception. Now this made sense because the ValueConstraint was being populated through a WPF Style but fooled us into thinking that somehow our tester’s machine (running XP) were incompatible with the Infragistics ValueConstraint control. Our DEV machines (running Windows 7) were all fine with the ValueConstraint control.

When we took the ValueConstraint control out (by commenting out the Style) the tester’s machine loaded a cut-down version of our app. fine, but that was only because the cut-down app no longer accessed app.config. Nothing to do with the actual ValueConstraint control at all.

After we removed the ValueConstraints we no longer got StaticMarkup Exception but we did get ConfigurationErrorException and that led us on a Phase 2 Journey Of Pain that, via Divide and Conquer, finally showed us that loading EntityFramework was the REAL real issue.

But not now.

Gloat.

So, bottom line: check that all the Sections expected by your Section Handlers are present. Go back to machine config and see what’s being loaded there and make sure everthing you are expecting to be installed is really installed.

EnterpriseLibrary ExceptionHandlingBlock EventLog Not Written

September 22, 2011

This is a bit of a newb ‘have you tied your shoelaces together’ kind of post, but since I fit the aforementioned category… what the heck…

Yeah, so my EventLogs were getting written, then later on they weren’t getting written, so what changed ?

Well I sat down and picked carefully through my app.config using the Enterprise Library Configuration Tool trying to see whether or not all the bits were connected properly. And what I think I saw was that the Logging Category of my Logging Exception Handler was set to ‘General’ but that under ‘Logging Settings’ the ‘General’ category did not have the Event Log Trace Listener added to it.

So I added ‘EventLogTraceListener’ to ‘General’ and simultaneously removed it from another category,’Logging Errors And Warnings’.

Except nothing happened…still no EventLog.

Except that when I closed my hosting app again and reopened the Configuration manager again and generally opened and closed the car doors in a futile attempt to make something change… it suddenly worked.

So Partial Huzzah (PHUZ)!. Nah, bugger it: HUZZAH!

That feels better.

ObjectDisposedException EntityFramework

September 21, 2011

I had a using clause around my call to Entity Framework like so:

using (var ctx = new SubstationLoadContext())
{
IRepository repo =
new Repository(ctx);

AreaSummations = repo.GetAreaSummationsWithEquipmentWithReadingUnits();
}

Subsequently while performing a LINQ query on AreaSummations I received the fiendish ObjectDisposedException. Porquoi ?

Some quick Googling told me that since my context variable was being disposed before I performed the query I should force the creation of an in-memory List in order to detach from the database i.e. I should do a .ToList() like so:

AreaSummations = repo.GetAreaSummationsWithEquipmentWithReadingUnits.ToList();

But my repo method was already doing a .ToList(). I was already detached from the database wasn’t I? Nyet.

The Botswanian Programming Legend masquerading as Mark Gravell on Stack Overflow informed me that the issue was that EF was lazily-loading some portion of the object graph and I needed to force an eager load by use of Entity Framework .Include. HUZZAH!

But I was already forcing an eager load wasn’t I ? See…

summations = (from s in ((SubstationLoadContext)repo.Context)
.SubstationGroupSummationTypes
.Include("Equipments.EquipmentReadingUnits")

Mais Non! I was NOT forcing an eager load because I had improperly specified the path to EquipmentReadingUnits. I had only included the path from about half-way up the object graph I needed to include the full path from the root Entity. Like so:
summations = (from s in ((SubstationLoadContext)repo.Context)
.SubstationGroupSummationTypes
.Include("SubstationGroup.Substations.Equipments.EquipmentReadingUnits")

PROPER HUZZAH! The eager load was correctly specified and ObjectDisposedException was banished!

Moral of the Story:

When getting ObjectDisposedException with Entity Framework make sure you have correctly specified the path for your eager loads. And include them if they are not already present. And then you will no longer see this

System.ObjectDisposedException: The ObjectContext instance has been disposed and can no longer be used for operations that require a connection


Follow

Get every new post delivered to your Inbox.