These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 
Author Message
 Post subject: Problem with Nhibernate/Reflection
PostPosted: Mon May 15, 2006 3:22 pm 
Beginner
Beginner

Joined: Mon Sep 26, 2005 5:57 pm
Posts: 39
I have a web application in production running successfully for months, and suddenly, one of the users is getting the error below. I am binding a collection of 'claimreview' objects to a gridview, and claimreview object has a primary key called Id of type int. The error is not making much sense to me. Please help

Object does not match target type.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Reflection.TargetException: Object does not match target type.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:


[TargetException: Object does not match target type.]
System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) +2329861
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +114
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29
System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component) +86

[TargetInvocationException: Property accessor 'Id' on object 'CID.IPath.NewBusinessLayer.claimreview' threw the following exception:'Object does not match target type.']
System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component) +370
System.Web.UI.WebControls.HyperLinkColumn.OnDataBindColumn(Object sender, EventArgs e) +292
System.Web.UI.Control.OnDataBinding(EventArgs e) +99
System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +206
System.Web.UI.Control.DataBind() +12
System.Web.UI.Control.DataBindChildren() +216
System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216
System.Web.UI.Control.DataBind() +12
System.Web.UI.Control.DataBindChildren() +216
System.Web.UI.Control.DataBind(Boolean raiseOnDataBinding) +216
System.Web.UI.Control.DataBind() +12
System.Web.UI.WebControls.DataGrid.CreateItem(Int32 itemIndex, Int32 dataSourceIndex, ListItemType itemType, Boolean dataBind, Object dataItem, DataGridColumn[] columns, TableRowCollection rows, PagedDataSource pagedDataSource) +200
System.Web.UI.WebControls.DataGrid.CreateControlHierarchy(Boolean useDataSource) +1519
System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e) +56
System.Web.UI.WebControls.BaseDataList.DataBind() +72
claim_review_display_enhanced.dispayReviews() +103
claim_review_display_enhanced.Page_PreRender(Object sender, EventArgs e) +7
System.Web.UI.Control.OnPreRender(EventArgs e) +2066972
System.Web.UI.Control.PreRenderRecursiveInternal() +77
System.Web.UI.Control.PreRenderRecursiveInternal() +161
System.Web.UI.Control.PreRenderRecursiveInternal() +161
System.Web.UI.Control.PreRenderRecursiveInternal() +161
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1360


Top
 Profile  
 
 Post subject:
PostPosted: Mon May 15, 2006 6:25 pm 
Expert
Expert

Joined: Fri May 13, 2005 5:56 pm
Posts: 308
Location: Santa Barbara, California, USA
please post class snippets showing member variable declaration, property getters/setters for CID.IPath.NewBusinessLayer.claimreview.Id.

Also post mapping file, and please double check the database tables and state the column definition for the Id column in the database table.

-devon


Top
 Profile  
 
 Post subject: I am having the same problem.
PostPosted: Tue Aug 29, 2006 10:03 am 
Newbie

Joined: Tue Aug 29, 2006 9:51 am
Posts: 8
Hi jbliss1234 ,
Were you able figure out the solution for you problem.

I am getting the same problem , In the code I am trying to execute a query and the query works from one workflow , but fails from another (but use to work from here too!).

Object does not match target type.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Reflection.TargetException: Object does not match target type.

Source Error:


Line 195:
Line 196: //get the results in arraylist
Line 197: arrResults = ArrayList.Adapter(query.List());
Line 198:
Line 199: switch (SortOrder)


[TargetException: Object does not match target type.]
System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target) +2330437
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +114
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29
System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture) +55
System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index) +18
NHibernate.Property.BasicGetter.Get(Object target) +75

[PropertyAccessException: Exception occurred getter of DomainManager.BusinessObjects.TbFolder.Id]
NHibernate.Property.BasicGetter.Get(Object target) +148
NHibernate.Persister.AbstractEntityPersister.GetIdentifier(Object obj) +120
NHibernate.Proxy.NHibernateProxyHelper.GetIdentifier(Object obj, IClassPersister persister) +103
NHibernate.Type.EntityType.ToString(Object value, ISessionFactoryImplementor factory) +201
NHibernate.Type.PersistentCollectionType.ToString(Object value, ISessionFactoryImplementor factory) +226
NHibernate.Impl.Printer.ToString(Object entity) +394
NHibernate.Impl.Printer.ToString(IEnumerator enumerator) +163
NHibernate.Impl.SessionImpl.FlushEverything() +1163
NHibernate.Impl.SessionImpl.AutoFlushIfRequired(ISet querySpaces) +70
NHibernate.Impl.SessionImpl.GetQueries(String query, Boolean scalar) +155
NHibernate.Impl.SessionImpl.Find(String query, QueryParameters parameters) +177
NHibernate.Impl.QueryImpl.List() +90
DomainManager.FeedsManager.GetFeedItemList(TbFeedSubscription Subscription, FeedItemSortOrder SortOrder) in C:\Project\KW Lite\Code\DomainManager\DomainManager\NonPersistant\FeedsManager.cs:197
DomainManager.FeedsManager.GetFeedItemList(Int32 SubscriptionID, FeedItemSortOrder SortOrder) in C:\Project\KW Lite\Code\DomainManager\DomainManager\NonPersistant\FeedsManager.cs:236
SS_Feeds.WucFeedListEx1_GetDataItem(Object sender, SSEventArgs e) in c:\Project\KW Lite\Code\SW\SS\Feeds.aspx.cs:244
FeedControl.Controls_wucFeedListEx.dlMain_ItemDataBound(Object sender, DataListItemEventArgs e) in c:\Project\KW Lite\Code\SW\Controls\wucFeedListEx.ascx.cs:191
System.Web.UI.WebControls.DataList.OnItemDataBound(DataListItemEventArgs e) +96
System.Web.UI.WebControls.DataList.CreateItem(Int32 itemIndex, ListItemType itemType, Boolean dataBind, Object dataItem) +172
System.Web.UI.WebControls.DataList.CreateControlHierarchy(Boolean useDataSource) +792
System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e) +75
System.Web.UI.WebControls.BaseDataList.DataBind() +86
FeedControl.Controls_wucFeedListEx.LoadData() in c:\Project\KW Lite\Code\SW\Controls\wucFeedListEx.ascx.cs:421
FeedControl.Controls_wucFeedListEx.LoadData(Int32 intMode) in c:\Project\KW Lite\Code\SW\Controls\wucFeedListEx.ascx.cs:428
SS_Feeds.DisplayFirstFolderContents() in c:\Project\KW Lite\Code\SW\SS\Feeds.aspx.cs:152
SS_Feeds.FeedInit() in c:\Project\KW Lite\Code\SW\SS\Feeds.aspx.cs:93
SS_Feeds.PageLoadEvent(Object sender, EventArgs e) in c:\Project\KW Lite\Code\SW\SS\Feeds.aspx.cs:58
CPageBase.Page_Load(Object sender, EventArgs e) in c:\Project\KW Lite\Code\SW\App_Code\Common\CPageBase.cs:92
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +31
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +68
System.Web.UI.Control.OnLoad(EventArgs e) +88
System.Web.UI.Control.LoadRecursive() +74
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3035



Thanks In Advance.


Top
 Profile  
 
 Post subject: Re: Problem with Nhibernate/Reflection
PostPosted: Sun Sep 10, 2006 12:30 pm 
Newbie

Joined: Sun Sep 10, 2006 12:27 pm
Posts: 13
jbliss1234 wrote:
I have a web application in production running successfully for months, and suddenly, one of the users is getting the error below.


Hi I have your same problem, is there some news?, have you found a solution?

Thank in advance


Top
 Profile  
 
 Post subject:
PostPosted: Wed Sep 13, 2006 5:10 pm 
Newbie

Joined: Tue Aug 29, 2006 9:51 am
Posts: 8
Hi jbliss1234 ,

Clear the session before what ever you are trying to do and try again.

tandonk


Top
 Profile  
 
 Post subject:
PostPosted: Mon Sep 25, 2006 11:22 pm 
Newbie

Joined: Mon Sep 25, 2006 11:02 pm
Posts: 10
Hi All,

I ran into this same error and created a work around I would like to share.

The error, "Object does not match target type" that jbliss posted, is caused because the IList you are trying to bind has objects of two different types: your base data object and the proxy for your data object. This occurs when some of the objects you retrieve in your list had proxies created for them previously in the session. If you are unfamiliar with NHibernate proxies, review the documenation concerning Lazy Loading.

The actual error occurs because some of the GridView columns (such as HyperLinkColumn in this case) cache the PropertyDescriptor based on the first object in the list. Instead of checking to see if the property exists on the second type, the framework throws an Exception. IMHO it should have checked if the property requested existed on the second type and continued if it did.

There is really no good solution for this. Clearing the session will clear out all of the proxies that have been previously created and then when you perform your query no proxy objects will be returned. However, clearing the session is not always possible.

The work-around I created was to actually create a class that will wrap all of the objects in a DynamicProxy class created using Castle.DynamicProxy. This proxy uses reflection to reroute calls to the underlying object. This solves the bug because it returns a new list with objects of only one type: the newly created proxy wrapper.

It can be implemented simply for a list or set:
Code:
gridview.DataSource = SafeDataBindingList<Project>.Create(listOfNhibernateObjects);

gridview.DataSource = SafeDataBindingSet<Project>.Create(SetOfNhibernateObjects);


A separate list with proxy wrappers is only created if there are objects of more than one type in the list, otherwise the original list is returned. This way we only incur the performance penalty when we need to avoid this bug.

The code for these classes is below. You will need to reference the Castle.DynamicProxy assembly to compile.


Code:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

using Castle.DynamicProxy;

namespace Interworks.NHibernateFramework
{
   public class SafeDataBindingList<T> : List<T>
   {
      private IList<T> _innerList;

      private SafeDataBindingList(IList<T> list) : base(list.Count)
      {
         _innerList = list;

         ProxyGenerator generator = new ProxyGenerator();

         foreach (T obj in list)
         {
            this.Add((T)generator.CreateClassProxy(typeof(T), new DataObjectInterceptor(obj)));
         }
      }

      public IList<T> InnerList
      {
         get { return _innerList; }
      }

      /// <summary>
      /// Creates a safe-wrapper around a list if needed for
      /// </summary>
      /// <param name="list"></param>
      /// <returns></returns>
      public static IList<T> Create(IList<T> list)
      {
         if (list.Count <= 1)
            return list;

         string t1 = "";
         string t2 = "";

         t1 = list[0].GetType().ToString();

         bool uniformList = true;
         for (int i = 1; i < list.Count; i++)
         {
            t2 = list[i].GetType().ToString();
            if (t1 == t2)
               continue;
            else
            {
               uniformList = false;
               break;
            }
         }

         if (uniformList)
            return list;

         return new SafeDataBindingList<T>(list);
      }
   }
}

using System;
using System.Collections.Generic;
using System.Text;

using Castle.DynamicProxy;

using Iesi.Collections.Generic;

namespace Interworks.NHibernateFramework
{
   public class SafeDataBindingSet<T> : HashedSet<T>
   {
      private ISet<T> _innerSet;

      private SafeDataBindingSet(ISet<T> set) : base()
      {
         _innerSet = set;

         ProxyGenerator generator = new ProxyGenerator();

         foreach (T obj in set)
         {
            this.Add((T)generator.CreateClassProxy(typeof(T), new DataObjectInterceptor(obj)));
         }
      }

      public ISet<T> InnerSet
      {
         get { return _innerSet; }
      }

      /// <summary>
      /// Creates a safe-wrapper around a list if needed for
      /// </summary>
      /// <param name="list"></param>
      /// <returns></returns>
      public static ISet<T> Create(ISet<T> set)
      {
         if (set.Count <= 1)
            return set;

         string t1 = "";
         string t2 = "";

         bool uniformSet = true;
         foreach (T obj in set)
         {
            if (t1 == "")
            {
               t1 = obj.GetType().ToString();
               continue;
            }

            t2 = obj.GetType().ToString();

            if (t1 == t2)
               continue;
            else
            {
               uniformSet = false;
               break;
            }
         }

         if (uniformSet)
            return set;

         return new SafeDataBindingSet<T>(set);
      }
   }
}

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

using Castle.DynamicProxy;

namespace Interworks.NHibernateFramework
{
   public class DataObjectInterceptor : IInterceptor
   {
      private static object _syncRoot = new object();
      private static Dictionary<string, MethodInfo> _methodCache = new Dictionary<string, MethodInfo>();
      private object _target = null;

      public DataObjectInterceptor(object target)
      {
         _target = target;
      }

      public object Intercept(IInvocation invocation, params object[] args)
      {
         // it's possible that the type that the proxy was built on is not the type of
         // the _target object.  If it is, simply invoke MethodInfo, if it's not, we have
         // to find the appropriate MethodInfo on the unknown type.
         if (invocation.Method.ReflectedType.ToString() == invocation.InvocationTarget.GetType().ToString())
         {
            return invocation.Method.Invoke(_target, args);
         }
         else
         {
            MethodInfo method = GetMethod(invocation);
            return method.Invoke(_target, args);
         }
      }

      private MethodInfo GetMethod(IInvocation invocation)
      {

         Type targetType = _target.GetType();

         string methodKey = GetMethodKey(targetType, invocation.Method.Name);

         if (_methodCache.ContainsKey(methodKey))
            return _methodCache[methodKey];
         else
         {
            MethodInfo methodInfo = null;
            if (invocation.Method.Name.StartsWith("get_") || invocation.Method.Name.StartsWith("set_"))
               methodInfo = GetPropertyMethod(targetType, invocation);
            else
            {
               methodInfo = GetMethod(targetType, invocation.Method.Name);
            }

            lock (_syncRoot)
            {
               if (methodInfo != null && !_methodCache.ContainsKey(methodKey))
                  _methodCache.Add(methodKey, methodInfo);
            }

            return methodInfo;
         }
      }

      private MethodInfo GetMethod(Type targetType, string methodName)
      {
         // search class hierarchy for method
         Type type = targetType;
         do
         {
            // Use DeclaredOnly to see if we can get the method directly from this type
            MethodInfo method = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            if (method != null)
               return method;

            type = type.BaseType;
         } while (type != null);

         return null;
      }

      private MethodInfo GetPropertyMethod(Type targetType, IInvocation invocation)
      {
         string propertyName = invocation.Method.Name.Split('_')[1];
         bool isGet = invocation.Method.Name.StartsWith("get_");

         Type type = targetType;
         PropertyInfo propertyInfo = null;

         do
         {
            propertyInfo = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);

            if (propertyInfo != null)
               break;

            type = type.BaseType;

         } while (type != null);

         if (propertyInfo == null)
            return null;

         if (isGet)
            return propertyInfo.GetGetMethod();
         else
            return propertyInfo.GetSetMethod();
      }

      private string GetMethodKey(Type targetType, string methodName)
      {
         return targetType.ToString() + "." + methodName;
      }
   }
}


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 6 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.