App can't Navigate to MainPage - c#

I'm facing the strange issue on my WP8.1 RT app - one of my beta testers reported that he sees black screen just after the splash screen. The app doesn't crash, hang the phone or other - just black screen instead of MainPage.
I've implemented some Trace methods inside the code to track the issue. The code looks like this:
// OnLaunched method that gets called when the App starts
protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
await Trace.WriteLineAsync(true, "Launched");
Frame rootFrame = CreateRootFrame();
await Trace.WriteLineAsync(true, "Before - better checkup");
if (rootFrame.Content == null)
{
await Trace.WriteLineAsync(false, "Rootframe content was null, navigating");
if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
await Trace.WriteLineAsync(false, "Navigation false");
else await Trace.WriteLineAsync(false, "Navigation was ok");
}
await Trace.WriteLineAsync(true, "After - better checkup");
Window.Current.Activate();
}
// Method creating the rootFrame:
private Frame CreateRootFrame()
{
Trace.WriteLineAsync(true, "Create Root frame");
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
Trace.WriteLineAsync(true, "Root frame was null");
rootFrame = new Frame();
SuspensionManager.RegisterFrame(rootFrame, "AppFrame");
rootFrame.NavigationFailed += OnNavigationFailed;
Window.Current.Content = rootFrame;
Trace.WriteLineAsync(false, "Window content {0}", Window.Current.Content.ToString());
}
return rootFrame;
}
The log the beta tester gets looks like this:
2014-10-06 13:02:56: Launched
2014-10-06 13:02:56: Create Root frame
2014-10-06 13:02:56: Root frame was null
Window content Windows.UI.Xaml.Controls.Frame
2014-10-06 13:02:57: Before - better checkup
Rootframe content was null, navigating
Navigation false
2014-10-06 13:02:57: After - better checkup
2014-10-06 13:03:01: App.cs suspending event
As you can see the most important line is Navigation false which means that
if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
await Trace.WriteLineAsync(false, "Navigation false");
Navigation returns false - I cannot navigate within my Frame, no crash, no hang - (Suspending event works), just can't get to MainPage. I have complately no idea what can be the source of the problem. Moreover - on my phone everything works, other devices also - both debug & release.
Does anybody have an idea why I cannot navigate to my MainPage?
Edit - navogation failed event added:
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
Trace.WriteLineAsync(true, "Failed to load page");
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}

Thanks to Nate Diamond comment I started searching for the cause of the problem little different way. I add this answer as it may help someone one day.
Finally after many attempts and help from the beta tester it turned out that the problem was caused by one of the variables that was initialized before the constructor of the Page. The initialization resulted in exception which was swallowed by Navigate method and thus it returned false.
The other thing is why the initialization resulted in exception, but that's the other story.

Related

IoTBrowser, navigate webview from task/thread

There's a webview:
<WebView x:Name="webView" Margin="0,10" Grid.RowSpan="3" LoadCompleted="webView_LoadCompleted"/>
And there's a basic snippet of code, which starts a task that will listen to an azure device. Some code is missing from the below example, presume the device was created normally.
The problem, is that I'd like to tell the Webview to navigate to a certain webpage, depending on the content of the received message.
The problem is,. "Window.Current" is null, so it crashes.
public App()
{
Task.Run(ReceiveC2dAsync);
}
private async static Task ReceiveC2dAsync()
{
while (true)
{
Microsoft.Azure.Devices.Client.Message receivedMessage = await deviceClient.ReceiveAsync();
if(receivedMessage != null)
{
// Snip
Task.Run(Navigate);
}
}
}
private async static Task Navigate()
{
try
{
if(Window.Current.Content != null)
((Frame)Window.Current.Content).Navigate(typeof(MainPage), "http://www.google.com");
}
catch(Exception e)
{
Debug.WriteLine("{0} Exception caught.", e);
}
}
In the override code:
protected override void OnLaunched(LaunchActivatedEventArgs e)
The following code can be used to navigate to a desired website when the application launches:
Frame rootFrame = Window.Current.Content as Frame;
if(rootFrame == null) rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage), "ms-appx-web:///help.html");
So, current is not null at this point.
If i save rootframe as a static, and use it at a later point in the task, I get a marshal error - basically stating the object is referenced to be marshaled to another thread.
My C# knowledge is,. in progress I fear.
So far I've been unable to find a proper explanation on how to have the webview respond to the internal task. Is it possible? And if so, how?
PS: The initial sample code is from: https://github.com/ms-iot/samples/tree/develop/IoTBrowser
The problem, is that I'd like to tell the Webview to navigate to a certain webpage
According to your code snippet, you are developing a UWP app. If you want to know how WebView navigate to a web site, you should be able to use Navigate method of WebView, for example:
webView.Navigate(new Uri("http://www.google.com"));
The following code can be used to navigate to a desired website when the application launches:
The code snippet by default inside OnLaunched navigate to one page by Frame. Frame control supports navigation to Page instances, not web pages, you cannot navigate to a website by Frame. Your above code snippet can only let the rootFrame navigate to MainPage, not the help.html. But you can get the ms-appx-web:///help.html parameter on MainPage and navigate to it by a WebView on MainPage.
I get a marshal error - basically stating the object is referenced to be marshaled to another thread.
If you want to invoke UIElement in a different thread, you should be able to use Core​Dispatcher, cannot invoke directly.
For a conclusion, I think what you actually want to do is navigate to a web site by WebView from a non UI thread. For example:
await Task.Run(Navigate);
private async Task Navigate()
{
try
{
await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
webView.Navigate(new Uri("http://www.google.com"));
});
}
catch (Exception e)
{
Debug.WriteLine("{0} Exception caught.", e);
}
}

uwp app crashed only in release mode due to recursion

I am creating a uwp app with some media and video features, I have tested the app repeatedly on debug mode and it works just perfect as desired, after commenting and uncommenting of some code I was able to figure out that recursion of a specific method is causing the app to crash.
I also tried to display the exception with message dialog ( for release mode ). But no exception caught and app just freezes and crashed.
I run the app once on debug mode and then stop visual studio and then just directly open the app from my PC to test it on release mode.
MyScenario:
I am using OnFileActivated event to open video files directly on double click in my PC with my app. That works just fine. Below I will show you the code and reason for crashing. Please let me know how to solve this.
Thanks in advance.
Code
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
//Some Media Stuff which works fine everytime even in release mode.
await speechRecognizer.CompileConstraintsAsync();// I am using speech input to play pause my media player.
ListenandAct();
}
private async void ListenandAct()
{
var result = await speechRecognizer.RecognizeAsync();
if (result.Text == "Pause" || result.Text == "pause")
{
Media.Pause();
}
else if (result.Text == "Play" || result.Text == "play")
{
Media.Play();
}
//ListenandAct(); //if I comment this line for recursion the app doesnt crash even in release mode, but If I uncomment it than app works perfect in debug mode but crashes in release mode.
}
OnFileActivated method in app.xaml.cs
protected async override void OnFileActivated(FileActivatedEventArgs args)
{
string ParentName = "";
if (args.Files.Count > 0)
{
Type TargetType = typeof(MainPage);
if (args.Files.Count == 1)
{
SingleFileToPlay = args.Files[0] as StorageFile;
TargetType = typeof(SingleFilePlay);
}
else if (args.Files.Count > 1)
{
ParentName = (await (args.Files[0] as StorageFile).GetParentAsync()).DisplayName;
MultiFilesToPlay = new List<StorageFile>();
TargetType = typeof(MultiFilePlay);
foreach (var file in args.Files)
{
MultiFilesToPlay.Add(file as StorageFile);
}
}
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();
rootFrame.NavigationFailed += OnNavigationFailed;
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
//if (rootFrame.Content == null)
//{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(TargetType, ParentName);
//}
// Ensure the current window is active
Window.Current.Activate();
}
}
NOTE
When I run a video file by double clicking it , it works perfect without crashing, but when my app is already running a video file and I double click another video file again then my app tries to run the second video file, the second video file is shown on the app as it is suposed to and then app freezes and crashes after a couple of seconds.

Issues resuming app with PickFolderAndContinue method

I am having issues resuming my app after utilizing the PickFolderAndContinue method. I've been trying to go off the directions from this MSDN sample. I haven't been able to figure out how to change the OnActivated method to return to my Settings page (the sample uses only the mainpage with different frames of content).
protected async override void OnActivated(IActivatedEventArgs e)
{
base.OnActivated(e);
ContinuationManager continuationManager = new ContinuationManager();
Frame rootFrame = CreateRootFrame();
await RestoreStatusAsync(e.PreviousExecutionState);
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(SettingsPage));
}
var continuationEventArgs = e as IContinuationActivatedEventArgs;
if (continuationEventArgs != null)
{
// What do i do here to return to my settings page?
Frame scenarioFrame = SettingsPage.Current.FindName("ScenarioFrame") as Frame;
if (scenarioFrame != null)
{
// Call ContinuationManager to handle continuation activation
continuationManager.Continue(continuationEventArgs, scenarioFrame);
}
}
Window.Current.Activate();
}
Thanks.
When your OnActivated is called if you know you always want to go to the SettingsPage then all you need is this code:
Frame rootFrame = CreateRootFrame();
await RestoreStatusAsync(e.PreviousExecutionState);
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(SettingsPage));
}
That code creates the applications root frame, and tells it to navigate to that specific page.
The code after this uses ContinuationManager. This is a mechanism set up to call into the page to let it know it is coming back from a AndContinue method. This will allow the page to do any functionality to occur for that Page.
FilePicker also has a ContinuationData property which you can set prior to calling the AndContinue method. This data is available in OnActivated via the IContinuationActivatedEventArgs.
This blog has a good description of the AndContinue Methods:
http://blogs.msdn.com/b/wsdevsol/archive/2014/05/08/using-the-andcontinue-methods-in-windows-phone-silverlight-8-1-apps.aspx

How to navigate to a page after the splash screen loads and before the grid template app loads C# XMAL Windows 8 store app?

this is my first time to use stackoverflow :) ,
I was working with grid template app in windows 8 store app and i wanted to add welcome page after the splash screen loaded , to do that i tried to add this statement
this.Frame.Navigate(typeof(WelcomePage));
to the OnLaunched method that was created by default with the grid template in the App.xmal.cs. after i created the Welcomepage it self and i created a button in the welcome page to navigate to the GroupedItemsPage.
My logic isn't working.
this is the default method code in the App.xmal.cs if that will help
protected override async void OnLaunched(LaunchActivatedEventArgs 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();
//Associate the frame with a SuspensionManager key
SuspensionManager.RegisterFrame(rootFrame, "AppFrame");
if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
// Restore the saved session state only when appropriate
try
{
await SuspensionManager.RestoreAsync();
}
catch (SuspensionManagerException)
{
//Something went wrong restoring state.
//Assume there is no state and continue
}
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame.Navigate(typeof(GroupedItemsPage), "AllGroups"))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}

Set startup form for Store App

I made a C# store app in Visual studio 2013. All of the sudden the startup form is changed, so its no longer the Mainpage. I cannot find how to resolve this problem.
I found a link where I could do something in the properties of my project, but I was unable to resolve the problem.
Does anyone know how to change the startup form for a C# store app in Visual Studio 2013?
edit: here is the OnLaunched method as told in comments.
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
#if DEBUG
if (System.Diagnostics.Debugger.IsAttached)
{
this.DebugSettings.EnableFrameRateCounter = true;
}
#endif
Frame rootFrame = Window.Current.Content as Frame;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
await CatalogApp.Common.SuspensionManager.RestoreAsync();
}
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
CatalogApp.Common.SuspensionManager.RegisterFrame(rootFrame, "appFrame");
// Set the default language
rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
}
// Place the frame in the current Window+
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
if (!rootFrame.Navigate(typeof(ShowItems), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
Window.Current.Activate();
}
There is probably is a navigation statement like: rootFrame.Navigate(typeof(ItemsPage), e.Arguments); in the
protected override async void OnLaunched(LaunchActivatedEventArgs e)
override in App.xaml.cs
If you are using this default, check typeof(ItemsPage) and the e.Argument statements.
Keep in mind, by default at activation,
the application redirects to the last opened window.
UPDATE
if (!rootFrame.Navigate(typeof(ShowItems), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
rootFrame.Navigate(typeof(MainPage), e.Arguments);
is a double navigation: first navigate to ShowItems, if succeeded navigate to MainPage. Why is that? I think this will lead to unexpected results.
Please try to remove
if (!rootFrame.Navigate(typeof(ShowItems), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
and check the results.
By the way: Which one is the page you want to start with?

Categories