Why does attempting to show a ViewModel throw an unhandled exception? - viewmodel

I'm using Visual Studio 2013 and MvvmCross to create an Android application using Portable Class Libraries. When I try and load a second ViewModel based on an action in the first View, an Unhandled Exception is being thrown.
In my first ViewModel, CatalogViewModel, I've got an ICommand called ShowCamera that is supposed to display the second ViewModel, CameraViewModel, when a button in the CatalogView is clicked.
In CatalogView.axml I've bound the button to the ShowCamera method in CatalogViewModel.
Right now the CameraViewModel is just an empty class but it inherits from MvxViewModel just like CatalogViewModel
And there's also a corresponding CameraView.cs and CameraView.axml.
Has anyone else ever encountered this or have any idea why the exception is being thrown. I've tried using a try/catch in the Get to see if I can get any more specific info about the unhandled exception without any luck (the catch block is never hit, the exception is always thrown on the ShowViewModel line).
Thanks in advance.

As Stuart pointed out it his comment, it was the lack of an [Activity] attribute on CameraView that was throwing the exception. The class definition for CameraView should be.
[Activity(Label="View for CameraViewModel")]
public class CameraView : MvxActivity
{
...
}
instead of
public class CameraView : MvxActivity
{
...
}
I initially thought about deleting the whole question out of embarrassment but decided to answer it and leave it here for anyone else who might encounter this situation in their own code.

Related

Avoiding binding errors when doing Xaml binding with ReactiveUI

I like ReactiveUI's code-based binding mechanisms. However, there are times when you need to use XAML bindings. In these cases, the DataContext needs to be set up properly between the View and ViewModel. I’ve been doing this in the View constructor:
public MyView()
{
InitializeComponent();
this.WhenActivated(disposables =>
{
this.DataContext = this.ViewModel;
...
});
}
This works, but I get errors in the output window at runtime:
System.Windows.Data Error: 40 : BindingExpression path error: ...
I'm using ReactiveUserControls, ViewModelViewHosts, and registering the View/ViewModel mappings in the Locator and letting ReactiveUI resolve them. I think I'm setting the DataContext as early as I can. So when I need to use XAML bindings - is there an alternative way of setting up the DataContext to avoid the phantom debug output errors?
The issue with what you have is you'll never adaptively get new versions of the ViewModel and you might get delayed subscriptions.
You are better off considering using the WhenAnyValue() operator eg:
this.WhenAnyValue(x => x.ViewModel).Bindto(this, x => x.DataContext);
Consider still playing it inside your WhenActivated() since that will avoid memory leaks, otherwise keep a reference to the IDisposable and disposing when your View has been closed.

How to set iAd Delegate to new View Controller

I am developing an application using Xcode 7 and Swift 2. I recently discovered an error in my code. In the debugger log (I think that is what it is called) , it printed this:
[AppDeveloper] ADBannerView: Unhandled error (no delegate or delegate does not implement didFailToReceiveAdWithError:): Error Domain=ADErrorDomain Code=7 "Ad was unloaded from this banner" UserInfo={ADInternalErrorCode=7, NSLocalizedFailureReason=Ad was unloaded from this banner, ADInternalErrorDomain=ADErrorDomain}
I did some research and found out that I needed this code:
iAdBannerView.delegate = self
In my viewDidLoad method. I tried it, and I no longer recieved the error. However, I have two viewControllers. Both contain iAds. In the original view controller, ViewController.swift, the code workds. In the view controller that I later added, AboutViewContoller, I get this error:
Cannot assign a value of type 'AboutViewController' to a value of type 'ADBannerViewDelegate?"
Could someone please show me my error in my code?
Earlier, I had:
class AboutViewController: UIViewController {
I forgot the ADBannerViewDelegate. The correct code is:
class AboutViewController: UIViewController, ADBannerViewDelegate {
Thanks to Charles A. and Daniel Storm for helping out!

SubreportProcessing event handler cannot access my viewmodel due to being on a different thread

I have a WPF application that is utilizing the reporting tools included with Visual Studio 2010. I've had some other problems that I've solved by creating a graph of objects that are all marked as serializable, etc., as mentioned on various other web pages.
The ReportViewer control is contained in a WindowsFormsHost. I'm handling the SubreportProcessing event of the ReportViewer.LocalReport object to provide the data for the sub report.
The object graph that I'm reporting on is generated in my viewmodel, and that viewmodel holds a reference to it. The SubreportProcessing handler is in my code behind of my window (may not be the best place - but I simply want to get the ReportViewer working at this point).
Here's the problem: In my event handler, I'm attempting to get a reference to my viewmodel using the following code:
var vm = DataContext as FailedAssemblyReportViewModel;
When the handler is called, this line throws an InvalidOperationException with the message The calling thread cannot access this object because a different thread owns it.
I didn't realize the handler might be called on a different thread. How can I resolve this?
I attempted some searches, but all I've come up with is in regards to updating the UI from another thread using the Dispatcher, but that won't work in this case...
I solved this problem using something I believe is a hack, by adding the following function:
public object GetDataContext() {
return DataContext;
}
And then replacing the line of code from my question with:
object dc = Dispatcher.Invoke(new Func<object>(GetDataContext), null);
var vm = dc as FailedAssemblyReportViewModel;
However, this seems like a hack, and I might be circumventing some sort of safety check the CLR is doing. Please let me know if this is an incorrect way to accomplish this.
That's a nasty problem you have there.
Why don't you use in the view a content presenter which you bind to a windows form host?
And in the view model you would have a property of type of type WindowsFormsHost. Also,in the view model's constructor you could set the windows form's host Child property with the report viewer.
After that is smooth sailing, you could use your report viewer anywhere in your code. Something like this:
View:
<ContentPresenter Content="{Binding Path=FormHost}"/>
ViewModel:
private ReportViewer report = new ReportViewer();
private WindowsFormsHost host = new WindowsFormsHost();
public WindowsFormsHost FormHost
{
get {return this.host;}
set
{
if(this.host!=value)
{
this.host = value;
OnPropertyChanged("FormHost");
}
}
}
public ViewModel() //constructor
{
this.host.Child = this.report;
}
After that happy coding. Hope it helps.

why getting null refence exception when giving iconuri in application bar?

in application bar firstly i given some images.when click on that icon need to assign new image.for that in click event wrote the bellow code.
private void searchbtn_Click(object sender, EventArgs e)
{
searchbtn.IconUri = new Uri("/Images/settings_high.png", UriKind.RelativeOrAbsolute);
}
Getting NULL Refernce exception.please help me
In case you did not know (I didn't) you must set the image Build Action property to Content, not resource. Then you can access the file like this:
StreamResourceInfo resourceInfo = Application.GetResourceStream(new System.Uri("ima1.png", UriKind.Relative));
If the stack trace shows a NullReferenceException directly in your method, that suggests that searchbtn is null.
I suggest you put a breakpoint on that line of code and run it in the debugger, then use the Auto window to check the value of searchbtn.
Is it possible that you've declared your own searchbtn variable while there's another similarly-named variable which actually has a reference to a button? The event handler name would suggest otherwise, but it's at least worth checking.
If the stack trace shows a NullReferenceException deeper in the code, that suggests there's a different problem. If you could post the full stack trace, that would help.

WP7 Application is being deactivated with no reason 10 seconds after navigating to a page

A WP 7.1 project starts with a Page that host a Panorama control. At some point user click on a ListBox, and this navigates the application to a details page.
In case the debugger is attached, everything stays on the screen as it should. But If I test an application either in emulator, or on the phone without a debugger, approximately in 5-10 seconds after the details page navigation, an application gets deactivated.
No unhanded exception, not closing, but deactivated even is raised. I have placed a message boxes in each of "exit handlers" to know exactly what happens and found out that it is deactivation.
No user input takes place after navigation and before the deactivation.
What may be the reason for such "no interaction" deactivation?
I don't call no "deactivate" requests from code.
Additional info:
Details page is bound to a sample view model that is obtained via MVVM Light ViewModel locator. View model locator gets it from ninject kernel that is a static public property of an App object(Yes, I have made IOC container publicly available via App property. I know it probably is a horrible practice, but I doubt the problem is linked to that). The page initializes just fine and displays all the data from a sample view model class. It almost seems like an app is deactivated due to inactivity, but there is no such thing in WP7 as far as I know.
UPDATE
A deactivation takes place exactly 10 seconds afer I call this line:
((PhoneApplicationFrame)(Application.Current.RootVisual)).Navigate(new Uri("/Views/BookDetailsView.xaml", UriKind.Relative));
from a view model of a main application view. The problem view is a details view, not the main one.
The constructor for BookDetailsView is empty (default):
public partial class BookDetailsView : UserControl
{
public BookDetailsView()
{
InitializeComponent();
}
}
The XAML for the view binds it's datacontext to a property of a mvvm light view model locator:
DataContext="{Binding Source={StaticResource Locator}, Path=BookDetails}"
The Locator resource is decleared in App.xaml and points to ViewModelLocator.cs.
The property that provides datacontext for a problem view is:
public static IBookDetailsViewModel BookDetailsStatic
{
get;
set;
}
/// <summary>
/// Gets the Main property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public IBookDetailsViewModel BookDetails
{
get
{
return BookDetailsStatic;
}
}
The BookDetailsStatic is initialized from the IoC container call in the ViewModelLocator ctor:
BookDetailsStatic = App.Kernel.Get<IBookDetailsViewModel>();
In a any scenario the call to get an IBookDetailsViewModel returns an instance of a
public class SampleBookDetailsViewModel: IBookDetailsViewModel
which has an empty constructor and a bunch of properties.
SOLVED
My view, that I have been navigating to, was declared as a UserControl, and should have been as PhoneApplicationPage.
Hard to say without knowing what's on the page, but you could be hitting the memory limit.
In general, you can consider the memory limit to be 90mb, but you're better off checking DeviceStatus.ApplicationMemoryUsageLimit and DeviceStatus.ApplicationCurrentMemoryUsage and possibly displaying it on screen every half second or so to debug.
You can also try the profiler, assuming it doesn't affect the repro.
BookDetailsView was decleared as a UserControl.
Navigating to a UserControl deactivates an application in 10 seconds.
Changing the type of a view to PhoneApplicationPage solves the problem.

Resources