none
Unable to cast System.Object[] to type System.Security.IPermission … at System.Linq.Enumerable.ToList() RRS feed

  • Question

  • I am trying to figure out and fix a crash (caused by InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'System.Security.IPermission') which is happening from time to time on our client PCs when the following code is executed:

    public List<Department> GetDepartmentList()
    {
        return DB.Departments.Where(d => d.Gender == SelectedGender && d.IsActive).ToList();
    }

    Why is this exception happening? How to fix that?

    I can not simply put it into try catch block because results from database are necessary.

    The code is executed on the main UI thread and no properties/methods are accessed from other threads as far as I know.

    Gender here is an EntityRef property inside Department entity class:

    [Column(Name = "FK_Gender")]
    public int? FK_Gender_Id;
    
    private EntityRef<Gender> gender;
    [Association(Name = "FK_Department_Gender", IsForeignKey=true, Storage="gender", ThisKey = "FK_Gender_Id")]
    public Gender Gender
    {
        get { return gender.Entity; }
        set { gender.Entity = value; }
    }

    GetDepartmentList is called from setter of SelectedGender property which is assigned when user clicks either Male or Female button on a UserControl through bound ICommand SelectGenderCommand:

    private RelayCommand selectGenderCommand;
    public ICommand SelectGenderCommand
    {
        get
        {
            return selectGenderCommand ?? (selectGenderCommand = new RelayCommand(param =>
                {
                    var genderName = param as string;
                    SelectedGender = DB.Genders.Single(g => g.Description == genderName);
                    ...
    
    private Gender selectedGender;
    public Gender SelectedGender
    {
        get { return selectedGender; }
        set
        {
            selectedGender = value;
            DepartmentList = GetDepartmentList();
            NotifyPropertyChanged(() => SelectedGender);
            ...
        }
    }

    DB is a DataContext derived class instance and it is initialized in the constructor of a ViewModel where the GetDepartmentList method is located:

    public InventoryItemSelectorViewModel(...
    {
        DB = new Database();
        DataLoadOptions dlo = new DataLoadOptions();
        dlo.LoadWith<Department>(d => d.Gender);
        DB.LoadOptions = dlo;
        ...

    The exception stack trace:

    System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'System.Security.IPermission'.
       at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)
       at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags)
       at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
       at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
       at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
       at System.Data.Linq.CommonDataServices.GetDeferredSourceFactory(MetaDataMember member)
       at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReaderBase`1.GetNestedLinkSource[T](Int32 iGlobalLink, Int32 iLocalFactory, Object instance)
       at Read_Department(ObjectMaterializer`1 )
       at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
       at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
       at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
       at GPFC.ROIPOS.ViewModels.InventoryItemSelectorViewModel.GetDepartmentList() in e:\Projects\POS - Develop\ROIPOS\ROIPOS\ViewModels\InventoryItemSelectorViewModel.cs:line 1173
       at GPFC.ROIPOS.ViewModels.InventoryItemSelectorViewModel.set_SelectedGender(Gender value) in e:\Projects\POS - Develop\ROIPOS\ROIPOS\ViewModels\InventoryItemSelectorViewModel.cs:line 202
       at GPFC.ROIPOS.ViewModels.InventoryItemSelectorViewModel.<get_SelectGenderCommand>b__12(Object param) in e:\Projects\POS - Develop\ROIPOS\ROIPOS\ViewModels\InventoryItemSelectorViewModel.cs:line 978
       at GPFC.ROIPOS.MVVM.RelayCommand.Execute(Object parameter) in e:\Projects\POS - Develop\ROIPOS\ROIPOS\MVVM\RelayCommand.cs:line 168
       at MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated)
       at System.Windows.Controls.Primitives.ButtonBase.OnClick()
       at System.Windows.Controls.Primitives.ToggleButton.OnClick()
       at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
       at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
       at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
       at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
       at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
       at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
       at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
       at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
       at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
       at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
       at System.Windows.Input.InputManager.ProcessStagingArea()
       at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
       at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
       at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
       at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
       at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
       at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
       at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

    One more detail which can be related to the question. Our application is running on several client PCs which all work with one local network database installed on one of the client PCs.


    GPAndrei

    Monday, October 19, 2015 7:01 PM

All replies

  • Hi GPAndrei ,

    According to your description, I suggest you can generate a new project and

    Reference Department class and Gender class, then you can test this Linq statement.

    public List<Department> GetDepartmentList()

    {

        return DB.Departments.Where(d => d.Gender == SelectedGender && d.IsActive).ToList();

    }

    Next, I guess maybe you need to source debugging for your code, you can refer to this blog ‘Using .NET Reference Source for debugging’.

    Last, for this case, whether all clients have this issue?

    Best Regards,

    Grady

    Wednesday, October 21, 2015 9:47 AM
  • Hi tracymgrady,

    Thank you for reply.

    How can it help generating a new project and testing in it if it is only occuring in this project in this specific situation? I can not reproduce the issue and I have no ability to debug/test on a client machine. This issue is happening on different client machines. And this is not the only one. I have several similar issues occuring in different places of the project inside linq to sql. These are strange exceptions which (as I think) may be caused by multithreading. But I verified all code in the project which uses multithreading and have not found any places where datacontext is accessed from multiple threads. Maybe I missed something. Can access to datacontext from diferent threads be the cause of these exceptions? What else can be the cause?

    I looked into .Net source code before asking this question but it looks like there is no source code for that specific method where the exception is occasionally occuring (it is defined as external):

    System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)

    ... so I can not check the code where conversion to IPermission is occuring.

    Other examples of similar kind exceptions:

    System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
       at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
       at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
       at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
       at System.Data.Linq.Table`1.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
       at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source, Expression`1 predicate)
    System.NullReferenceException: Object reference not set to an instance of an object.
       at System.Security.PermissionSet.FastIsEmpty()
       at System.Security.PermissionSet.IsSubsetOfHelper(PermissionSet target, IsSubsetOfType type, IPermission& firstPermThatFailed, Boolean ignoreNonCas)
       at System.Security.FrameSecurityDescriptor.CheckSetDemand2(PermissionSet demandSet, PermissionSet& alteredDemandSet, RuntimeMethodHandleInternal rmh, Boolean fDeclarative)
       at System.Security.FrameSecurityDescriptor.CheckSetDemand(PermissionSet demandSet, PermissionSet& alteredDemandSet, RuntimeMethodHandleInternal rmh)
       at System.Security.SecurityRuntime.FrameDescSetHelper(FrameSecurityDescriptor secDesc, PermissionSet demandSet, PermissionSet& alteredDemandSet, RuntimeMethodHandleInternal rmh)
       at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags)
       at System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags)
       at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes, StackCrawlMark& stackMark)
       at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
       at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture)
       at System.Data.Linq.CommonDataServices.GetDeferredSourceFactory(MetaDataMember member)
       at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReaderBase`1.GetNestedLinkSource[T](Int32 iGlobalLink, Int32 iLocalFactory, Object instance)
       at Read_BuyBackInventoryItem(ObjectMaterializer`1 )
       at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
       at System.Linq.Enumerable.<OfTypeIterator>d__aa`1.MoveNext()
       at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source)
       at System.Data.Linq.CommonDataServices.GetObjectByKey(MetaType type, Object[] keyValues)
       at System.Data.Linq.DataContext.Refresh(RefreshMode mode, IEnumerable entities)
       at System.Data.Linq.DataContext.Refresh(RefreshMode mode, Object entity)
    System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.NullReferenceException: Object reference not set to an instance of an object.
       at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
       at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
       at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
       at System.Data.Linq.Table`1.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
       at System.Linq.Queryable.Single[TSource](IQueryable`1 source, Expression`1 predicate)
    System.NullReferenceException: Object reference not set to an instance of an object.
       at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
       at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
       at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
       at System.Data.Linq.DataQuery`1.System.Linq.IQueryProvider.Execute[S](Expression expression)
       at System.Linq.Queryable.SingleOrDefault[TSource](IQueryable`1 source)
    One more detail. It looks like all these exceptions are occuring right after switching wpf UserControls (or showing wpf window). Can incorrect switching be the cause of these exceptions?

    I appretiate your help.


    GPAndrei



    • Edited by GPAndrei Wednesday, October 21, 2015 6:01 PM
    Wednesday, October 21, 2015 2:55 PM