WPF Binding Exception - wpf

We have a WPF application using Prism 6.0 which have different screens that show collections. Many of these views are loaded in the startup and shown as necessary.
Sporadically, we are getting an exception in the startup. The exception call-stack does not give any useful information (except that it is a cross thread collection access issue) and we are finding it difficult to find the root cause. The exception is as below
at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
at System.Collections.Generic.List`1.get_Item(Int32 index)
at System.Collections.ObjectModel.Collection`1.get_Item(Int32 index)
at System.Collections.ObjectModel.ReadOnlyCollection`1.System.Collections.ICollection.CopyTo(Array array, Int32 index)
at System.Collections.ArrayList.InsertRange(Int32 index, ICollection c)
at System.Collections.ArrayList.AddRange(ICollection c)
at System.Collections.ArrayList..ctor(ICollection c)
at System.Windows.Data.ListCollectionView.<RefreshOverride>b__1_0()
at MS.Internal.Data.SynchronizationInfo.AccessCollection(IEnumerable collection, Action accessMethod, Boolean writeAccess)
at System.Windows.Data.BindingOperations.AccessCollection(IEnumerable collection, Action accessMethod, Boolean writeAccess)
at System.Windows.Data.ListCollectionView.RefreshOverride()
at System.Windows.Data.CollectionView.RefreshInternal()
at System.Windows.Data.CollectionView.RefreshOrDefer()
at System.Windows.Data.ListCollectionView.ProcessCollectionChanged(NotifyCollectionChangedEventArgs args)
at System.Windows.Data.CollectionView.ProcessChangeLog(ArrayList changeLog, Boolean processAll)
at System.Windows.Data.CollectionView.ProcessInvoke(Object arg)
at MS.Internal.Data.DataBindOperation.Invoke()
at MS.Internal.Data.DataBindEngine.ProcessCrossThreadRequests()
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
Is there any way to which collection (at least the type of collection elements) is causing this issue or any way to find the root cause?
Any ideas are welcome!
thank you

This exception is usually thrown when the index used to access the collection is less than zero or equal to or greater than the collection's Count.
A cross-thread exception would usually be of type NotSupportedException.
You must ensure that the index is within the range.
To find the exact location you must go to the Debug menu and enable the debugger to break on all exceptions and then run you application in debug mode:
Press Ctrl+Alt+E and tick the "Common Language Runtime Exceptions" check box
Run in debug mode to make the program halt at the line of origin (in case of proper exception handling)
From your exception message it looks like the stack trace is generated from a release build.
In this case make sure you publish the PDB files too (debug symbols). This will allow the exception stack trace to include line numbers.
Another option is to review all your index based collection access (read) and guard against an index out of range (it should be standard in production code). You could use the occasion to do this for index based write access too. You can use the search tool to locate indexers in your solution.
Even if you include PDB files or use the debug mode to identify the line of origin, you should consider to review your code base for other brittle index based collection access with the help of the search tool. And maybe add a rule to your coding guide to force developers to check the collection bounds before accessing it by index.

Related

Isolated Storage Exception in silverlight

I've isolated storage in my silverlight application to store some information for specific users.
On every login, I check storage space by using
IsolatedStorageFile.GetUserStoreForApplication()
After that I store some information in local variable and then clear all storage and get it again by using these lines
IsolatedStorageFile.GetUserStoreForApplication().Remove();
IsolatedStorageFile.GetUserStoreForApplication();
Sometimes I get error on IsolatedStorageFile.GetUserStoreForApplication(). Error detail is
System.IO.IsolatedStorage.IsolatedStorageException was caught
Message=Initialization failed.
StackTrace:
at System.IO.IsolatedStorage.IsolatedStorageFile.FetchOrCreateStore(String groupName, String storeName, IsolatedStorageFile isf)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStore(String group, String id)
at System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication()
Error occurs randomly but when it happens,I lost my all data in storage. I don't know the reason of this error and didn't find any helpful article. I also found many related questions but my problem is still there.
Edit: I just got to know the reason of this behavior and that is According to this
If any of the directories or files in the store are in use, the removal attempt for the store fails. Any subsequent attempts to modify the store throw an IsolatedStorageException exception. In this case, you must ensure that the files or directories are explicitly deleted.
But I did find any method to explicitly delete whole store. Can anyone suggest me any solution?

The operation cannot be completed because the DbContext has been disposed, PagedList

Using ASP.NET MVC and Entity, I keep getting the "The operation cannot be completed because the DbContext has been disposed.".
Using the UnitOfWork pattern along with a GenericRepository.
The Exception happens in PagedList.PagedListExtensions.ToPagedList.
I tried to use AsNoTracking, without any result.
How to avoid those exception to happens, as it crash the client's interface with an Internal Error.
Most likely you aren't asking to enumerate the query until after the context is disposed. LINQ to Entities doesn't actually execute queries until you ask to enumerate the query, i.e. see each item in the result set. ToPagedList sounds like exactly the sort of thing that requires enumeration.
The fix is to force enumeration of the query sometime before disposing of the context (in the Repository probably), by calling .ToList() on it.

Using a custom DataAbortHandler in WindowsCE

We're developing an application based on Windows CE. At the moment we're fighting with numerous data abort exceptions that only occur with release builds. We only have a limited number of development devices, that actually output their debug stream onto the serial port. Now we're wondering if it is possible to use OemDataAbortHandler to access the content of the Exception (i.e. everything that is written to the debug stream) in order to gather the data for diagnostic purposes.
Ideally we'd be able to create a textfile containing data like this:
Exception 'Data Abort' (4): Thread-Id=05a70002(pth=8252169c),
Proc-Id=03cf000e(pprc=824f3d70) 'XXXX.exe', VM-active=03cf000e(pprc=824f3d70) 'XXXX.exe'
PC=400323cc(coredll.dll+0x000223cc) RA=4003361c(coredll.dll+0x0002361c) SP=0102f27c,
BVA=6464646c
Now, the signature of OemDataAbortHandler is:
void OEMDataAbortHandler(void);
Is there any way to get access to the data written to the debug stream?
You should be able to use Structured Exception Handling (__try/__except) to filter the data abort exception. The processor state at the time of the exception is returned in the CONTEXT argument of the GetExceptionInformation intrinsic function. See the documentation for try/except.

How to find out the exact operation that is posted to Dispatcher

Is there a way where we can find out which UI element has posted an operation to the Dispatcher queue which eventually throws the event ,System.Windows.Threading.Dispatcher.CurrentDispatcher.Hooks.OperationPosted
Update : A private property DispatcherOperation.Name is showing what I need in the VS mouse-over in debugging mode. I just need to print this name to a logger for other debugging purposes. Is it possible to extract the Name dynamically.
Yes it is possible, while i give you a way to do it, i must warn you though, using reflection to get private or protected fields/properties/methods is never a good idea because first they are usually private for a reason and second of all if the signature or interface changes you code might break. But because you said it is just for debugging, this might be a valuable solution.
You can always use Reflection for these kind of things. First you need the Type and Instance of the object you want to read its private properties. Unfortunately i don't know if the Name you are looking for is a field or a property, but the overall procedure is similar. First get the property with GetProperty and then call GetValue on the returned PropertyInfo object. You might want to cache the PropertyInfo object to gain some speed while debug. You also need to use the correct BindingFlags again i don't know exactly how the field/property is described so i can't give you the exact code, but from here it should be easy to figure out.
Hope that helps.

"The calling thread must be STA, because many UI components require this." Error in WPF?

I am creating a xps document as below.
Assembly assembly = Assembly.GetExecutingAssembly();
//read embedded xpsDocument file
Stream helpStream = assembly.GetManifestResourceStream(resourceNameOfContext);
if (helpStream != null)
{
Package package = Package.Open(helpStream);
string inMemoryPackageName = "memorystream://" + topicName + ".xps";
Uri packageUri = new Uri(inMemoryPackageName);
//Add package to PackageStore
PackageStore.AddPackage(packageUri, package);
docXps = new XpsDocument(package, CompressionOption.Maximum, inMemoryPackageName);
}
return docXps;
When i am trying to get docXps.GetFixedDocumentSequence();
I am getting the above error. Can anyone help?
Thanks,
Your problem has nothing to do with the code surrounding the creation or use of the XPS document. It has everything to do with what thread you are running under.
You will receive the The calling thread must be STA, because many UI components require this error whenever any of the following are attempted on a MTA thread:
You construct any object derived from FrameworkElement (including Controls and Panels)
You construct any object derived from BitmapEffect
You construct any object derived from TextComposition
You construct any object derived from HwndSource
You access the current InputManager
You access the primary KeyboardDevice, StylusDevice, or TabletDevice
You attempt to change the focus on a FrameworkContentElement
You provide mouse, keyboard or IME input to any control that accepts text input
You make WPF content visible or update its layout
You manipulate the visual tree in such a way as to cause a re-evaluation for rendering
Several other changes, mostly having to do with display and input
For example, I received this error last year when I tried to deserialize some XAML that contained <Button> and other WPF objects from within a WCF service. The problem was simple to solve: I just switch to a STA thread to do the processing.
Obviously most work with XPS documents will trigger one or more of the above conditions. In your case I suspect that GetFixedDocumentSequence ends up using TextComposition or one of its subclasses.
No doubt the my solution of switching to a STA thread will also work for you, but first you need to figure out how your code that works with XpsDocuments is getting executed run from a MTA thread. Normally any code from from the GUI (eg a button press) is automatically run in a STA thread.
Is it possible that your code that manipulates XPS Documents may be being executed without a GUI? From a user-created thread? From a WCF service or a web service? From an ASPX page? Track that down and you'll probably find your solution.
If that doesn't work, let us know the details of the path through which GetFixedDocumentSequence is called, so we can diagnose it. The directly surrounding code isn't nearly as important as the call stack and how it is originally being invoked. If it is hard to explain you probably should add a call stack to prevent misunderstandings and help us diagnose the problem further, or tell you how to start a STA thread in your particular situation.
Is your code trying to access the xps doc from a background thread? If this is the case, you'll want to use the dispatcher. Info on that here.
If this doesn't help, could you post the code where you're actually calling GetFixedDocumentSequence()?

Resources