MvvmCross with Template10 - mvvmcross

I'm attempting to create a version of the UWP app for the TipCalc sample here: https://github.com/MvvmCross/MvvmCross-Samples/tree/master/TipCalc
There already is a UWP version in the sample, which works fine. However I'm attempting to use Template10 (https://github.com/Windows-XAML/Template10) and I am having trouble getting the two libraries to work together.
MvvmCross wants me to modify the OnLaunched method, which has a reference to the root Frame. However, Template 10 instead abstracts this method exposing OnStartAsync which has no such reference...
There is an override in Template 10 for CreateRootFrame which seems like the right place to initialize the mvvmcross app, but this doesn't appear to work the way I expected...
Although the launched app DOES navigate to the appropriate page, and does also appear to initialize the view model (a breakpoint on the Start method in the associated VM does get hit), the page itself is blank.
comparing the Visual Tree of both apps reveals that while the existing UWP app from the sample has a Frame:
my Template10 App is loading a Modal Dialog:
I forked the original sample project and added the template 10 version, if you wish to try it for yourself: https://github.com/selaromdotnet/MvvmCross-Samples
Has anyone else been able to integrate MvvmCross with template 10? do you have any idea what i'm doing wrong, and any advice for the best practices in using both of these libraries together?

hmm it turns out that the ModalDialog is the expected behavior for Template10, according to the current docs here: https://github.com/Windows-XAML/Template10/wiki/Docs-|-Bootstrapper
I'm not familiar enough with Template10 to say why this is the case, but it does also say you can change this by overriding OnInitializeAsync, which I did, restoring the original frame in the same way the regular UWP project does:
public override async Task OnInitializeAsync(IActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
var setup = new Setup(rootFrame);
setup.Initialize();
}
await Task.CompletedTask;
}
This did the trick! I'm sure I still have a ways to go (I believe Template10 has it's own way of restoring state, so I probably shouldn't be doing it here)...
but this at least change finally got me to a working app. IF you know more about what I'm doing incorrectly here or what I should be doing instead, your comments would be greatly appreciated, thanks!

Related

Implement Template10 Controls will result in an unhandled XAML exception

I have some problems to implement Template10 controls in my UWP project.
When I create a PageHeader control into my MainPage.XAML, I can see the control, edit the control and run the application. But unfortunately the application will break until the components initialize.
There´s no error description.
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
UnhandledException += (sender, e) =>
{
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
};
endif
}
Visual studio will highlight this line.
What am I doing wrong ?
When I run the Template10 Hamburger template, everything seems to be working fine.
I hope you can help me to understand how template10 is working.
I´ve seen your MVA contents but for me it wasn´t clear how to use template10 in existing projects.
don't forget with this control it sort of needs other things to function correctly. 1 key item is a Frame from which is created at start of the application based on the NavigationServiceFactory if you reference the samples you will see what I am referring to. To drop it in an existing app and expect to run without some modifications, you should expect errors.
I would suggest referencing samples and other things associated. the nuget package can be install to any new project or existing with the right configurations set. theoretically you could set the Frame = {x:null} it should work but I haven't done it or needed to. Or don't set it at all, it's part of the back navigation tracking that the control watches for.
if you hover over the "e" in the method handler inside the ( ), you can look at the errors... e = exception :P, you might have to dig alittle.

How should RenderTargetBitmap be used?

In a Windows Universal App (WinRT) application, I am trying to capture a bitmap image of the current page (or a portion of it).
A google search indicated that I should use the class Windows::UI::Xaml::Media::Imaging::RenderTargetBitmap (more specifically its method RenderAsync() ) to capture the screen.
In a small sample application, I thus added this code (C++) :
auto pclRenderTargetBitmap = ref new Windows::UI::Xaml::Media::Imaging::RenderTargetBitmap;
Concurrency::create_task(pclRenderTargetBitmap->RenderAsync(pclElem,100,100)).then([&]() {
// handling code here
});
(pclElem is a FrameworkElement, more specifically a canvas, and is not null)
When I execute this code, the task is indeed created, but the lambda in the "then" is never called. It's as if RenderAsync() never terminates.
Does anyone have any experience with using this function in C++ ? What am I missing ?
Thanks for your answers.
Thanks to Andy Rich for his answer.
The problem was that the pclRenderTargetBitmap was going out of scope.
This can be solved by passing the lambda parameters by value :
auto pclRenderTargetBitmap = ref new Windows::UI::Xaml::Media::Imaging::RenderTargetBitmap;
Concurrency::create_task(pclRenderTargetBitmap->RenderAsync(pclElem,100,100)).then([=]() {
// handling code here
});

Flash ActionScript - Trace from background Worker

Is it possible at all, or traces are part of the API which is not avalible from background Worker?
Consider this code:
public class Main extends Sprite {
public function Main(container : DisplayObjectContainer = null)
{
if(Worker.current.isPrimordial) {
trace("isPrimordial");
var m_worker : Worker = WorkerDomain.current.createWorker(this.loaderInfo.bytes);
m_worker.start();
}
else {
trace("is NOT Primordial");
}
}
The string "is NOT Primordial" does not appear, however I do see that m_worker.state is "WorkerState.RUNNING".
Some UPDATE: The main thread works and racts to events, however it appears like the backgroung worker does not start until I desconnect the debugger.
And if it is possible, how do I setup the fdb to show these logs?
PS. Im using flash standalone debug player 13 with latest FDT and Apache Flex 4.12.1 SDK.
Ok, so the results for now are:
The background thread (Worker) can write traces with no problems at all if the debugger is not attached, for example if we are using flashlog.txt for the output (output to file).
What is required is: flash debug player (me used v. 14 stand alone and firefox versions).
The setup for using text file as output discussed here:
http://helpx.adobe.com/flash-player/kb/configure-debugger-version-flash-player.html
http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf69084-7fc9.html
Correct location of mm.cfg on modern operating systems (and not on Win95!) discussed here:
https://forums.adobe.com/thread/1218258
For me the output to file started to work only after the flashlog.txt file was created by some 3rd party tool (I used Vizzy), but probably it is a permission problem of flasho n windows 8 and the file just can be created manually.
Detailed discussion of the flash traces topic (althoug a little old, but mostly still relevant) is here:
See trace() of Flash when running in browser
Thanks everyone for help.
Create a static Log class that output it's log to trace. Use this log class in your main thread and in your worker. Only the main thread log definition will be used allowing to trace from anywhere.

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.

When should I load data in a Windows Phone 8 application?

I've seen a lot of questions here related to the OnNavigatedTo method, but none of them seem to answer the basic question of, "At what point should I load data?" The documentation on MSDN doesn't explicitly answer this question, as far as I can tell.
If I need to load a list of data from the local database, which method is the most appropriate to use? Should I use the OnNavigatedTo method, or the Loaded event?
What I've been using so far is this pattern, which seems to work well:
protected override void OnNavigatedTo(NavigationEventArgs e) {
base.OnNavigatedTo(e);
if (NavigationMode.New == e.NavigationMode) {
var data = LoadData();
this.DataContext = data;
}
}
What this means is that for a new instance of a page, load the data synchronously. This also means that the page will not be rendered until the data has finished loading and the profiler complains that I'm using too much UI thread time.
An alternate approach is this pattern:
protected override async void OnNavigatedTo(NavigationEventArgs e) {
base.OnNavigatedTo(e);
if (NavigationMode.New == e.NavigationMode) {
var data = await LoadData();
this.DataContext = data;
}
}
But with this pattern, it seems to me that navigation, and therefore page rendering may occur before I've loaded the data and set the DataContext, meaning unnecessary re-paints and what-not.
I usualy bind to a ViewModel directly in XAML. Then in OnNavigatedTo I trigger the view model to fetch its data async.
This allows me to show basic values from start (page title etc.). Then when I start fetching the data I can also activate a progressbar directly in the ViewModel and then remove it once the data is fetched.
I recommend you load your data asynchronously. OnNavigatedTo is one place where you can start the loading. If you're talking about a page that the user is almost certainly going to navigate to, then you may be able to start loading earlier.
I have a series of blog posts that look at how async has some friction with traditional OOP. There are a couple of posts that look at data binding in particular, e.g., asynchronous construction (the section on asynchronous initialization) and asynchronous properties (the section on data binding).
Just a few hours ago I announced the first stable release for my AsyncEx library, which includes the NotifyTaskCompletion types that you can use to kick off an asynchronous loading operation and have your view respond automatically (via data binding) when it completes.
But back to the core problem: you do have to show something while the data is loading. I recommend you do not consider this "unnecessary", but rather accept it as an opportunity to provide a better user experience. Think about what you want your app to look like on a slower phone or if there is an error loading the data. Any time there's I/O, design the "Loading..." and "Error" states as well as the "Loaded" state.