ServiceLocationProvider is null when launched as a Share Target - windows-runtime

I'm using MVVM Light and everything is fine except when launching my Windows Phone 8.1 WinRT app as a Share Target.
When I try to assign MainViewModel viewModel = ServiceLocator.Current.GetInstance<MainViewModel>(); I get an exception for ServiceLocator.Current.
Exception Message: ServiceLocationProvider must be set.
Do I need to do something extra in App.xaml.cs OnShareTargetActivated event to insure the Locator is running?
UPDATE:
A ShareTarget page needs to be thought of as a small extension of your app. It seems that not all of the app's resources are loaded (including app-wide resources in App.xaml). So I just created a new instance of MainViewModel in the share page's constructor, loaded only the things I need for the share to complete, save the information and call ShareOperation.ReportCompleted. This returns the user back to the app that is sharing.
I still haven't found a good solution for getting other resources in my ViewModel, but this works for now.

This indicates that the following line has not been executed:
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
This line will instruct the ServiceLocator class to use the SimpleIoc.Default instance as its ServiceLocator.Current. When you run your app as a Share target, the initialization is slightly different and probably the ViewModelLocator doesn't get initialized. You need to find a good location to perform the initialization before you use the ServiceLocator.
Cheers
Laurent

Related

Portable Class Library - Windows Store App: "Could not load file or assembly Microsoft.Threading.Task"

I have an MVVM Light infrastructure which is all contained within a Portable Class Library targeting .Net 4, SL5, Win 8, WP 8.1, WPSL 8, Xamarin.Android and Xamarin.iOS. This works perfectly with a WPF client, however, when I try and use it in a Windows Store App/Win 8 environment I am coming up against some resistance. The first issue is found in App.xaml:
<Application
x:Class="Win8Client.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:INPS.Vision.Appointments.Shared.ViewModels"
xmlns:local="using:Win8Client">
<Application.Resources>
<vm:ViewModelLocator x:Key="Locator" />
</Application.Resources>
</Application>
At design time I get "Could not load file or assembly 'Microsoft.Threading.Tasks', version=1.0.12.0 ..." which is referring to my ViewModelLocator. This compiles and appears to run ok but I don't get any design time data. The design time data works fine in the WPF client.
Once running I see my first view but once this line gets called:
Slots = await _appointmentsDataProvider.GetAppointments(SelectedDate);
I get the following exception in the setter of my slots property which takes advantage of MVVM Lights Set method of ViewModelBase. The Slots property is NOT bound to any UI yet.
Exception:
"The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"
Slots Property:
public List<Slot> Slots
{
get { return _slots; }
set
{
Set(SlotsPropertyName, ref _slots, value); // <-- Exception thrown here
}
}
Realised I haven't actually asked a question. Simply, I would like to know, what is the best approach for using MVVM Light with a Windows Store App?
Thanks in advance for any help or advice!
The first issue "Could not load file or assembly 'Microsoft.Threading.Tasks', version=1.0.12.0 ..." I haven't worked out yet but from time to time I do see the design data. Seems very temperamental...
The second issue - The reason this through me a bit was because is "just worked" in WPF and I assumed it would just work in a Windows Store App. Wrong. It looks like Windows Store Apps handle async/await threading differently - that's my guess.
Fix: Created an IDispatcherHelper interface in PCL with a single method declaration:
void RunOnUIThread(Action action);
Then created a single concrete DispatcherHelper class in each platform specific project (WPF/Windows 8.1) which implement IDispatcherHelper. Each implementation simply calls MVVM Lights:
DispatcherHelper.CheckBeginInvokeOnUI(action);
In App.xaml.cs in the WPF and Windows 8.1 I simply registered the concrete implementations with MVVM Lights SimpleIoc with the IDispatcherHelper as the handle. Within the view model I then use the platform specific implementations through the interface:
var slots = await _appointmentsDataProvider.GetAppointments(SelectedDate);
IDispatcherHelper dispatcherHelper = SimpleIoc.Default.GetInstance<IDispatcherHelper>();
dispatcherHelper.RunOnUIThread(() =>
{
Slots = slots;
});
Got to love abstraction!

Can an embedded cocos2d-js app call back out to c++?

I'm researching the possibility of using cocos2d-js by embedding it as a view inside an existing iOS app. In order to make this work, I'm going to need 2-way communication between cocos2d and the surrounding application.
After some initial investigation, I have determined that it is possible to call in to cocos using ScriptingCore:
ScriptingCore* sc = ScriptingCore::getInstance();
jsval outVal;
sc->evalString("function()", &outVal);
My question, then, is around doing the reverse. It is possible to (e.g. in response to user input) call back out of cocos2d-js to C++? Ideally, there would be a way to register a callback with ScriptingCore which could be invoked from JavaScript.
I believe it can be done, but I have not tried myself, nor can I find a good and concise example.
All I can do is point you at SuperSuraccoon's Bluetooth example and it's git page, which apparently does both ways communication between C++ and JS code.

Prism with WinRT how can I force a fresh start when resuming from termination?

I am building a WinRT App, that uses proximity, and WiFi direct for peer to peer communication. As a result, when the app terminates, and then resumes I need it to start fresh (the connections will be closed, and can't be reopened without user interaction). The problem is that the Prism MvvmAppBase class that I am inheriting my app from is doing something that is causing it to try to resume from a saved state (that does not exist) and the app ends up on the last screen shown, but there is no ViewModel backing it, and so depending on the view, it will just sit unresponsive, or crash.
I am looking at this guide for guidance, and it says that unless there is a way to start fresh, but I cannot seem to find how to actually do that. http://msdn.microsoft.com/en-us/library/windows/apps/xx130647.aspx
I have been hacking around in the App.cs file to try and get it to work. There is really nothing at all in the App.cs file now except for the unity container and prism bootstrapping, and a call to NavigationService.Suspending() in the Suspending event handler.
The bootstrapping looks like this, but it is never called when the app is resumed from Termination.
protected override async void OnLaunchApplication(LaunchActivatedEventArgs args)
{
await BootStrapper.Config(_container);
await BootStrapper.RegisterPrismInstances(_container, NavigationService, SessionStateService, FlyoutService);
NavigationService.Navigate("Main", null);
}
If anyone has dealt with this before, and can point me in the right direction, I would really appreciate it.
When a Prism WinRT app is re-launched after being Terminated Prism will try to restore the application state, the Frame's navigation stack and the Frame's state before being terminated (which will navigate to the last opened page and try to restore any properties in the view model that are marked with the RestorableState attribute.)
By looking at the MvvmAppBase's source code it seems that there are a couple of things you could try to prevent Prism for saving / restoring the application state:
Create a default constructor in your App class that would clear the handlers of the Suspending event. The default constructor of the MvvmAppBase registers to this event and saves the state when it's raised.
Override the OnLaunched method of the base class. In it, after executing the base method, check if the previous executing state is Terminated. If so, you could clear the navigation history of the NavigationService and navigate to your start up page. The saving and restoring operations will still execute though, so any registered service will still be restored to its previous state. (This cannot be done in the OnLaunchApplication as it's not invoked if the application's state was successfully restored.)
Also, you could also try to completely remove this functionality from the MvvmAppBase class. However, most of its methods related to saving / restoring the application state are private, so you might as well drop the MvvAppBase, copy its entire code in your App class and edit it accordingly.
I have not tried any of the approaches listed above so I'm unaware if they could generate any problem, but they might help you as a starting point.

Windows Phone 8 Return value from getresponseCallBack method?

I am trying to make a generic connectivity class in my Windows Phone 8 app. This class should be used whenever i need to send a POST request to the service.
In a particular use case i need to call the service, display the response and navigate the user away from the current page.
I am able to successfully achieve the first 2 objectives using the connectivity class. This is because the connectivity class is not part of the UI. So is there a way the GetResponseCallBack method can inform the calling method that it has received the response and then i can navigate the user?
Hope i was able to ask my question clearly.
Thanks!
I have managed to find a work-around for now. Not sure if it is the right way to get the response of the async task. But i am sharing it for the benefit for others who may be facing similar issue.
What i have done is, i have defined the GetResponseCallBack as a public method in the class calling the async task method. Later i pass the same GetResponseCallBack as a parameter to the beginGetResponse method in the GetRequestStreamCallBack method.
This way i am able to bring the control flow back to the phoneApplicationPage after the asyncTask executes, thus allowing me to handle some events on the UI thread.
Hope it helps!

Use MessageDialog/MessageBox with Portable Class Library and MVVM Light

I´m developing an App that will be available for Windows Phone 8 and the Windows Store. To reduce redundancy I´m using a Portable Class Library (PCL) and on top of that I'm trying to apply the MVVM pattern with the help of the MVVM Light PCL Toolkit. The ViewModels are placed in the PCL and are bound directly in the XAML of the Apps pages.
When the data is received without an error, everything works fine. But I don´t know how to get the exceptions/error message back to the App when errors do happen.
Inside the Windows Store App errors will show as a MessageDialog while the Wp8 App will use the MessageBox class. Obviously the PCL isn´t aware of any of these classes. What I´m not getting is how to know if a ViewModel ran into an error, and how to get the message inside the App. Is this even possible when the ViewModels are bound inside the XAML?
The code in the ViewModel (inside the PCL) looks like this:
DataService.Authenticate((token, error) =>
{
if (error != null)
{
// This is, obviously, not going to work.
MessageBox.Show(error.Message);
return;
}
Token = token;
});
So I have to save the error somehow and let the App itself know the error has occurred, and then call the matching way of showing the error to the user.
Currently I´m thinking of something like defining an Error-property inside the BaseViewModel and fill it when errors in the ViewModel occur. Then, in the CodeBehind of the pages, make them aware of the current ViewModel and bind a PropertyChanged-event to this Error-property. But I was not able to implement it yet, so I don't know if this is even the right way to go.
Do I have to step down from the idea to bind the ViewModels inside the XAML, and do I instead have to initialize them inside the pages Codebehind?
Your instinct is correct, but there are more than a few ways of going about this.
First and foremost, you can use Mvvm's Messaging library, which will allow your ViewModel to send messages directly to your View. Your View can then handle it in any way it wishes, including but not limited to using a MessageDialog.
Secondly, you can also create a Function or Action (likely the former) in your ViewModelLocator for ShowMessageDialog. This Function will likely take a string and return a Task. Then, after you initialize your ViewModelLocator initially, you can inject your ShowMessageDialog code. Your ViewModels can then use whatever platform's MessageDialogs that they please.
Ex:
Note: This code uses the BCL Async libraries that are accessible in Nuget. They work in the PCL just fine.
ViewModelLocator:
public static Func<string, Task> ShowMessageDialog { get; set; }
App.xaml.cs:
ViewModelLocator.ShowMessageDialog = (message) =>
{
// For Windows Phone
return TaskFactory.StartNew(() => MessageBox.Show(message));
// For Windows 8
MessageDialog md = new MessageDialog(message);
return md.ShowAsync().AsTask();
};
ViewModel:
await ViewModelLocator.ShowMessageDialog("This is my message.");
Secondary Note: The md.ShowAsync().AsTask(); must be run on the UI Thread. This means that you will have to invoke it via the dispatcher in the case that you are running it in a task asynchronously. This is possible using a similar method of injecting the use of the app's CoreDispatcher via the RunAsync method.
This means that you can, on any platform (Windows 8 and Windows Phone shown above), inject whatever Message Dialog system you want and use it in your PCL.
I would say that it is much easier to do the first method I suggested, as that is what it is there for, but the Function method version is definitely helpful at times.