New Posts New Posts RSS Feed: System.Reflection.TargetInvocationException in Silverlight Model
  FAQ FAQ  Forum Search   Calendar   Register Register  Login Login

System.Reflection.TargetInvocationException in Silverlight Model

 Post Reply Post Reply
Author
kdev View Drop Down
Groupie
Groupie
Avatar

Joined: 03-Jan-2013
Posts: 83
Post Options Post Options   Quote kdev Quote  Post ReplyReply Direct Link To This Post Topic: System.Reflection.TargetInvocationException in Silverlight Model
    Posted: 09-Apr-2014 at 9:21am
Hi,

I am using Cocktail, Devforce 2012 7.2.2 and I have a codeFirst model.

When I try to preload my entities using cocktail, one of my entity use an abnormal amount of time to import only 7 entities into my entityManager's cache !!
Following to the log below, it takes ~6s to import them. 

(DEBUG SL) 16:32:28.187 : MyApp.Common.PreLoadRepository`1:OnManagerCreated : PreLoadRepository<MyApp.Module.Domain.Entities.ModeTraitment>.Seed() imported 0 entites in 0.9998 ms. : ThreadId(1)
(DEBUG SL) 16:32:28.226 : MyApp.Common.PreLoadRepository`1:OnManagerCreated : PreLoadRepository<MyApp.Module.Domain.Entities.Motif>.Seed() imported 23 entites in 33.0001 ms. : ThreadId(1)
(DEBUG SL) 16:32:28.230 : MyApp.Common.PreLoadRepository`1:OnManagerCreated : PreLoadRepository<MyApp.Module.Domain.Entities.Attribut>.Seed() imported 0 entites in 1.0002 ms. : ThreadId(1)
Une exception de première chance de type 'System.NullReferenceException' s'est produite dans MyApp.Module.Domain.tn.SL
Une exception de première chance de type 'System.Reflection.TargetInvocationException' s'est produite dans mscorlib.dll
Une exception de première chance de type 'System.NullReferenceException' s'est produite dans MyApp.Module.Domain.tn.SL
Une exception de première chance de type 'System.Reflection.TargetInvocationException' s'est produite dans mscorlib.dll

...

Une exception de première chance de type 'System.NullReferenceException' s'est produite dans MyApp.Module.Domain.tn.SL
Une exception de première chance de type 'System.Reflection.TargetInvocationException' s'est produite dans mscorlib.dll
(MyApp DEBUG SL) 16:32:34.958 : MyApp.Common.PreLoadRepository`1:OnManagerCreated : PreLoadRepository<MyApp.Module.Domain.Entities.TypeInterv>.Seed() imported 7 entites in 6726.06 ms. : ThreadId(1)
(MyApp DEBUG SL) 16:32:34.972 : MyApp.Common.PreLoadRepository`1:OnManagerCreated : PreLoadRepository<MyApp.Module.Domain.Entities.TypeIdentity>.Seed() imported 2 entites in 10.0012 ms. : ThreadId(1)

All the exception shown in the logs happen during the execution of : entityManager.ImportEntities(entities, MergeStrategy.OverwriteChanges) on this entity : TypeInterv

This entity use TPH. TypeInterv inherit of a base class named RefenceBase. The Preloader also loads many entities which also inherit of this base class (ModeTraitment, Attribut, ...) without any problem !

The entity looks like this :

[DataContract(IsReference = true)]
public class TypeInterv : ReferenceBase
{
    [DataMember]
    [Required]
    public bool ForProf { get; set; }

    [DataMember]
    [Required]
    [Taux]
    public decimal TauxRet { get; set; }
    
    [DataMember]
    public RelatedEntityList<Tarif> Tarif { get { return null; } }
}

I tried to cleanup the entity to find out what could be the issue. If I remove the RelatedEntityList I still get the exceptions and the excessive execution time.
If I remove the TWO properties (only one doesn't fix it), I no longer get the exceptions and the entities imports in 7ms.


What could cause the issue ? I am guessing something related to the code injected by postsharp ?


Note : The entity have a basic Configuration class :

    public class TypeIntervConfiguration: EntityTypeConfiguration<TypeInterv>
    {
        public TypeIntervConfiguration()
        {
            Map(e =>
                    {
                        e.ToTable(Cst.Tables.TblReferenceBase);
                        e.Requires(Cst.Fields.Discriminant)
                            .HasValue(Cst.ReferenceBase.DiscriminantTypeInterv);
                    });

            Property(p => p.ForProf)
                .HasColumnName(Cst.Fields.TypeIntervForProf);
            Property(p => p.TauxRet)
                .HasColumnName(Cst.Fields.TypeIntervTauxRet);
        }
    }

The attribute Taux is an EF Convention (I tried to test without the attribut and it doesn't fix it)

    public class TauxConvention: Convention
    {
        /// <summary>
        /// Constructeur
        /// </summary>
        public TauxConvention()
        {
            this.Properties()
                .Where(x => x.GetCustomAttributes(false).OfType<TauxAttribute>().Any())
                .Configure(c => c.HasPrecision(18, 8));
        }
    }


Any idea ?

Back to Top
DenisK View Drop Down
IdeaBlade
IdeaBlade


Joined: 25-Aug-2010
Posts: 715
Post Options Post Options   Quote DenisK Quote  Post ReplyReply Direct Link To This Post Posted: 09-Apr-2014 at 2:49pm
Hi Kdev,

are you able to catch and drill into the exception?

I'd like to see a stack trace on where this is occurring in DevForce.
Back to Top
kdev View Drop Down
Groupie
Groupie
Avatar

Joined: 03-Jan-2013
Posts: 83
Post Options Post Options   Quote kdev Quote  Post ReplyReply Direct Link To This Post Posted: 09-Apr-2014 at 2:55pm
Hi denisk

I can't catch the exception, it must be handled in the importEntities. Unless there a way to do it that i am not aware of ?
Back to Top
DenisK View Drop Down
IdeaBlade
IdeaBlade


Joined: 25-Aug-2010
Posts: 715
Post Options Post Options   Quote DenisK Quote  Post ReplyReply Direct Link To This Post Posted: 09-Apr-2014 at 3:32pm
You can try turning on all CLR exceptions and manually drill in when the NullRefEx occurs.
Back to Top
kdev View Drop Down
Groupie
Groupie
Avatar

Joined: 03-Jan-2013
Posts: 83
Post Options Post Options   Quote kdev Quote  Post ReplyReply Direct Link To This Post Posted: 10-Apr-2014 at 1:35am
Below the differents exceptions raised :

L'exception System.NullReferenceException s'est produite
  Message=La référence d'objet n'est pas définie à une instance d'un objet.
  StackTrace:
       à MyApp.Module.Domain.Entities.TypeInterv.get_ForProf()
  InnerException: 


L'exception System.Reflection.TargetInvocationException s'est produite
  Message=Une exception a été levée par la cible d'un appel.
  StackTrace:
       à System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       à System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
  InnerException: System.NullReferenceException
       Message=La référence d'objet n'est pas définie à une instance d'un objet.
       StackTrace:
            à MyApp.Module.Domain.Entities.TypeInterv.get_ForProf()
       InnerException: 


L'exception System.NullReferenceException s'est produite
  Message=La référence d'objet n'est pas définie à une instance d'un objet.
  StackTrace:
       à MyApp.Module.Domain.Entities.TypeInterv.get_Taux()
  InnerException: 


L'exception System.Reflection.TargetInvocationException s'est produite
  Message=Une exception a été levée par la cible d'un appel.
  StackTrace:
       à System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
       à System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
  InnerException: System.NullReferenceException
       Message=La référence d'objet n'est pas définie à une instance d'un objet.
       StackTrace:
            à MyApp.Module.Domain.Entities.TypeInterv.get_Taux()
       InnerException: 


While debugging with all CLR exception ON, the exception did put a breakpoint in the internal constructor of the base classe which looks like this :

    [DataContract(IsReference = true)]
    public abstract class ReferenceBase: KatekAuditEntity
    {
        internal ReferenceBase()
        {
            Actif = true;  <--- The exception happens here 
        }
        
        ....
    } 

I did put this line in comment. All the exceptions did disapeer and the import was fast as excepted !

Are we not allowed to put code in a constructor of a base class with Devforce ? Is this a limitation ? An issue with postsharp ?
Note : I tried to change the visibility of the constructor from internal to protected and the issue still exists.



Back to Top
DenisK View Drop Down
IdeaBlade
IdeaBlade


Joined: 25-Aug-2010
Posts: 715
Post Options Post Options   Quote DenisK Quote  Post ReplyReply Direct Link To This Post Posted: 10-Apr-2014 at 11:05am
Can you post a code snippet for the property Actif?
Back to Top
kdev View Drop Down
Groupie
Groupie
Avatar

Joined: 03-Jan-2013
Posts: 83
Post Options Post Options   Quote kdev Quote  Post ReplyReply Direct Link To This Post Posted: 10-Apr-2014 at 11:21am
it's just a bool property, no specific code.

Here is the full code of tyhe Entity

 [DataContract(IsReference = true)]
    public abstract class ReferenceBase: KatekAuditEntity
    {
        protected ReferenceBase()
        {
            Actif = true;
        }

        [DataMember]
        [Required]
        public int Id { get; set; }

        [DataMember]
        [Required]
        public bool Actif { get; set; }

        [DataMember]
        [Required]
        [StringLengthVerifier(MaxValue = CommonCst.Strings.Code)]
        public string Code { get; set; }

        [DataMember]
        [Required]
        [StringLengthVerifier(MaxValue = CommonCst.Strings.LblCourt)]
        public string Libelle { get; set; }

        [DataMember]
        [Required]
        public DateTime DateDebut { get; set; }

        [DataMember]
        [Required]
        public DateTime DateFin { get; set; }

        [DataMember]
        public RelatedEntityList<RefInvisible> RefsInvisibles { get { return null; } }

        [DataMember]
        [Required]
        [ForeignKey("TypeInterne")]
        public int TypeInterne_Discriminant { get; set; }

        [DataMember]
        [Required]
        [ForeignKey("TypeInterne")]
        public string TypeInterne_Code { get; set; }

        [DataMember]
        public TypeInterne TypeInterne { get; set; }

        public override string ToString()
        {
            return Libelle;

        }

        #region EntityPropertyNames
        public partial class EntityPropertyNames
        {
            public const string RefsInvisibles = "RefsInvisibles ";
            public const string TypeInterne = "TypeInterne";
        }
        #endregion EntityPropertyNames    
    }
Back to Top
DenisK View Drop Down
IdeaBlade
IdeaBlade


Joined: 25-Aug-2010
Posts: 715
Post Options Post Options   Quote DenisK Quote  Post ReplyReply Direct Link To This Post Posted: 10-Apr-2014 at 11:52am
Can you try making the ReferenceBase non-abstract and see if the NullRefEx still occurs?
Back to Top
kdev View Drop Down
Groupie
Groupie
Avatar

Joined: 03-Jan-2013
Posts: 83
Post Options Post Options   Quote kdev Quote  Post ReplyReply Direct Link To This Post Posted: 10-Apr-2014 at 12:07pm
Still the same issue when I remove the abstract keyword.
Back to Top
DenisK View Drop Down
IdeaBlade
IdeaBlade


Joined: 25-Aug-2010
Posts: 715
Post Options Post Options   Quote DenisK Quote  Post ReplyReply Direct Link To This Post Posted: 10-Apr-2014 at 1:04pm
Ok. I think at this point if you can isolate that to a small test solution, I'd be able to investigate further.
Back to Top
kdev View Drop Down
Groupie
Groupie
Avatar

Joined: 03-Jan-2013
Posts: 83
Post Options Post Options   Quote kdev Quote  Post ReplyReply Direct Link To This Post Posted: 11-Apr-2014 at 2:52am
hi DenisK,

Here is a repro project uploads/1623/TargetInvocationExceptionBis.zip . The exception happen when the entity is created.


also, on this project I noticed when the entitymanager is created, there is another internal exception in devforce. Seems it is looking for and assembly named IdeaBlade.EntityModel.Web which doesn't exists in the nuget packages ...

L'exception System.IO.FileNotFoundException s'est produite
  _HResult=-2147024894
  _message=Impossible de charger le fichier ou l'assembly 'IdeaBlade.EntityModel.Web, Version=7.2.2.0, Culture=neutral, PublicKeyToken=287b5094865421c0' ou une de ses dépendances. Le fichier spécifié est introuvable.
  HResult=-2147024894
  IsTransient=false
  Message=Impossible de charger le fichier ou l'assembly 'IdeaBlade.EntityModel.Web, Version=7.2.2.0, Culture=neutral, PublicKeyToken=287b5094865421c0' ou une de ses dépendances. Le fichier spécifié est introuvable.
  Source=mscorlib
  FileName=IdeaBlade.EntityModel.Web, Version=7.2.2.0, Culture=neutral, PublicKeyToken=287b5094865421c0
  FusionLog==== Informations d'état de liaison préalable ===
JRN : DisplayName = IdeaBlade.EntityModel.Web, Version=7.2.2.0, Culture=neutral, PublicKeyToken=287b5094865421c0
 (Fully-specified)
JRN : Appbase = file:///C:/Dev/Ideablade/Bugs/TargetInvocationExceptionBis/TargetInvocationExceptionBis/bin/Debug/
JRN : PrivatePath initial = NULL
Assembly appelant : IdeaBlade.Core, Version=7.2.2.0, Culture=neutral, PublicKeyToken=287b5094865421c0.
===
JRN : cette liaison démarre dans le contexte de chargement de default.
JRN : utilisation du fichier de configuration de l'application : C:\Dev\Ideablade\Bugs\TargetInvocationExceptionBis\TargetInvocationExceptionBis\bin\Debug\TargetInvocationExceptionBis.vshost.exe.Config
JRN : utilisation du fichier de configuration d'hôte : 
JRN : utilisation du fichier de configuration de l'ordinateur à partir de C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
JRN : référence post-stratégie : IdeaBlade.EntityModel.Web, Version=7.2.2.0, Culture=neutral, PublicKeyToken=287b5094865421c0
JRN : tentative de téléchargement de la nouvelle URL file:///C:/Dev/Ideablade/Bugs/TargetInvocationExceptionBis/TargetInvocationExceptionBis/bin/Debug/IdeaBlade.EntityModel.Web.DLL.
JRN : tentative de téléchargement de la nouvelle URL file:///C:/Dev/Ideablade/Bugs/TargetInvocationExceptionBis/TargetInvocationExceptionBis/bin/Debug/IdeaBlade.EntityModel.Web/IdeaBlade.EntityModel.Web.DLL.
JRN : tentative de téléchargement de la nouvelle URL file:///C:/Dev/Ideablade/Bugs/TargetInvocationExceptionBis/TargetInvocationExceptionBis/bin/Debug/IdeaBlade.EntityModel.Web.EXE.
JRN : tentative de téléchargement de la nouvelle URL file:///C:/Dev/Ideablade/Bugs/TargetInvocationExceptionBis/TargetInvocationExceptionBis/bin/Debug/IdeaBlade.EntityModel.Web/IdeaBlade.EntityModel.Web.EXE.

  StackTrace:
       à System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
       à System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks)
  InnerException: 

Back to Top
DenisK View Drop Down
IdeaBlade
IdeaBlade


Joined: 25-Aug-2010
Posts: 715
Post Options Post Options   Quote DenisK Quote  Post ReplyReply Direct Link To This Post Posted: 15-Apr-2014 at 6:19pm
Thanks for the sample.

After further investigation, it turns out that the exception is expected which explains why it's being internally handled by DF.

It's not currently being classified as a bug because we have a reason to implement it this way.

To avoid the NullRefEx, you may want to move the initialization of "Actif" to your sub-type classes' constructor instead.

The missing assembly exception is also being internally handled and it's safe to be ignored as well.


Back to Top
kdev View Drop Down
Groupie
Groupie
Avatar

Joined: 03-Jan-2013
Posts: 83
Post Options Post Options   Quote kdev Quote  Post ReplyReply Direct Link To This Post Posted: 16-Apr-2014 at 1:45am
Hi Denis,

OK. So no code at all in the constructor of an abstract class. Always put (duplicate !) the code in a no abstract sub class. It can become boring when you have lots of sub-sub-sub-class like I do. The risk to forget to initialize some fields is there. Anyway, I can live with that.

But what is really bothering me here is that devforce handled it internally but it has a very HUGE impact on the performance. Don't forget that in this case for 7 entities we are talking about 7 milliseconds without exception versus 6 seconds with exceptions !!!
To handle them internally it's nice but not at this cost. Knowing the side effect of these exceptions, 100% of the time I will prefer to get an exception on my side to force me to fix my code rather than to have this HUGE downfall performance (which is almost impossible to identify).

When I see all the others exception internally handled by devforce (see my other post http://www.ideablade.com/forum/forum_posts.asp?TID=4678&title=invalidoperationexception-while-accessing-a-navigation-property) I wonder if those also have an impact on the performance of my application (which I currently suspect).
What can I do to avoid all these costly exceptions (see other post) ? How can I know what I should or not write ?

Note : in my opinion the "no code policy" in an abstract constructor should be added to the documentation and specify that otherwise it could have an impact on the performance of application.
Back to Top
DenisK View Drop Down
IdeaBlade
IdeaBlade


Joined: 25-Aug-2010
Posts: 715
Post Options Post Options   Quote DenisK Quote  Post ReplyReply Direct Link To This Post Posted: 17-Apr-2014 at 11:19am
Yes, I agree that the workaround can be tedious and easily forgettable. Thank you for bringing that to my attention. After further discussion with the lead engineer, we have decided to classify this as a bug due to the performance hit. We'll try to find a way to see if we can detect the NullRefEx for this specific case ahead of time so it doesn't throw an exception.

We will respond to your other post.

In general, we try our best to only handle exception internally if we have to and if we see that there's no visible cost to performance. Thanks to you, this specific case proves that we have to modify our handling of the NullRefEx.


Edited by DenisK - 17-Apr-2014 at 11:35am
Back to Top
 Post Reply Post Reply

Forum Jump Forum Permissions View Drop Down