OnSuspending event not triggered with UWP Windows 10 - c#

The OnSuspending event is not triggered for my UWP app but this problem only occurs on Windows Phone running Windows 10. It works as expected when running it as a Windows Store app on my local machine or the simulator.
I'm using this event to save my app's settings when the app is closing, but this is obviously causing a major problem for windows phone since this event is not triggered.
As you can see, the OnSuspending event is initialized when the app starts
public App()
{
Microsoft.ApplicationInsights.WindowsAppInitializer.InitializeAsync(
Microsoft.ApplicationInsights.WindowsCollectors.Metadata |
Microsoft.ApplicationInsights.WindowsCollectors.Session);
this.InitializeComponent();
this.Suspending += OnSuspending;
}
Below is the OnSuspending code that should be called but isn't when running in Windows Phone 10.
private async void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
await Locator.MainPageViewModel.SaveSettings();
deferral.Complete();
}
Any ideas on how I can resolve this or is there a potential work-around?
Thanks.
UPDATE-1:
When I terminate my app by holding the flag key and click on the cross to terminate it, is closes the app but it still doesn't trigger the OnSuspending event, but the .net IDE still runs. When I press F5 to run the app again, it then triggers the OnSuspending event. My app starts but the code stops running in the IDE.

From the official App lifecycle documentation:
A note about debugging using Visual Studio: Visual Studio prevents Windows from suspending an app that is attached to the debugger. This is to allow the user to view the Visual Studio debug UI while the app is running. When you're debugging an app, you can send it a suspend event using Visual Studio. Make sure the Debug Location toolbar is being shown, then click the Suspend icon.
That means that the OnSuspending event won't get fired while you are attached to the Visual Studio debugger. If you want to debug it, manually send the event by selecting the respective Lifecycle Event.

Related

Setting Label.Text too frequently causes an app crash - Xamarin.Forms

I am working on an MQTTnet application for mobile/wearable devices. I've tested my code in both a standard C# Console application and .Net Core application, both work as expected. The issue I am having is when I port the code to Xamarin Forms, for running on a Galaxy Watch. The app will run for a few seconds, but then it will crash. I believe it could be from assigning the Label text too often?
I have an MQTT publisher device pumping out a simple position value at a 10ms interval. Where my other apps will just keep chugging along, the app in Xamarin will lock and then eventually crash. If it comment out the Label.Text assignment, the app keeps running without a crash.
Here is my Xamarin code, is there a better way to handle the assignment?
// Event Handler to the ApplicationMessageRecevied event
client.ApplicationMessageReceived += (s, e) =>
{
StatusLabel.Text = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
};
I found that using the following to assign the label works well. My publisher is sending messages at 2ms intervals, and the watch is stable!
Device.BeginInvokeOnMainThread(() => {
PositionData.Text = Encoding.UTF8.GetString(e.ApplicationMessage.Payload);
});

Force WPF application to maximize on Windows startup

I have a WPF app that installed on Windows 10 Pro via ClickOnce and uses MahApps.Metro.
It is set to launch on Windows boot with a non-admin account that has no password. Tablet mode is enabled.
I want the application pop up full screen to create kiosk-like experience, however the app starts minimized when launching on boot. To clarify, the WindowState is Maximized, but Windows does not show it, instead it shows the start screen. It launches fullscreen maximized when launching manually.
Here is some code, however I guess this is more of a configuration problem than code problem:
This is how I set the launch on boot:
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey(#"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
string startPath = Environment.GetFolderPath(Environment.SpecialFolder.Programs)
+ #"\Publisher\AppName.appref-ms";
rkApp.SetValue("AppName", startPath);
This is MainWindow.xaml
<Controls:MetroWindow x:Class="AppName.MainWindow"
IgnoreTaskbarOnMaximize="True" ShowTitleBar="False" WindowStyle="None" WindowState="Maximized">
...
</Controls:MetroWindow>
Take a look at Kiosk Mode for Windows 10.
From Set up a device for anyone to use (kiosk mode):
A single-use device is easy to set up in Windows 10 for desktop
editions (Pro, Enterprise, and Education). For a kiosk device to run a
Universal Windows app, use the assigned access feature. For a kiosk
device (Windows 10 Enterprise or Education) to run a Classic Windows
application, use Shell Launcher to set a custom user interface as the
shell.
From Assigned access (Industry 8.1):
Administrators can use assigned access to restrict a user account to
access a single application. You can use assigned access to set up
single-function devices, such as restaurant menus or displays at trade
shows.
The following table identifies the type of application that can be used on each Windows 10 edition to create a kiosk device.
A Universal Windows app is built on the Universal Windows Platform
(UWP), which was first introduced in Windows 8 as the Windows Runtime.
A Classic Windows application uses the Classic Windows Platform (CWP)
(e.g., COM, Win32, WPF, WinForms, etc.) and is typically launched
using an .EXE or .DLL file.
You can do this in the MainWindow.xaml.cs by adding a windowstate of maximized.
public MainWindow()
{
InitializeComponent();
this.WindowState = WindowState.Maximized;
}
The solution (hack) was to open any other window (e.g. powershell) on startup using Task Scheduler, and after another window is open, we can call Alt+Tab in a powershell script using.
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait("%{TAB}")
Set the Window state in the ContentRendered event handler:
protected override void OnStartup(StartupEventArgs e)
{
Application.Current.MainWindow.ContentRendered += (s, a) =>
Application.Current.MainWindow.WindowState = WindowState.Maximized;
}

WebBrowser control never fires DocumentCompleted event

I have a following code inside windows forms application but web_DocumentCompleted event never fires on my windows 10 machine
What's bothering me is that the same code works just fine if I compile it and run it on my VPS (windows server 2012R2), or machine which has windows 8.1 installed.
All machines have Internet Explorer 11 installed.
public Form1()
{
InitializeComponent();
//Web Browser control
this.web.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(web_DocumentCompleted);
this.web.Navigate(URL);
}
void web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
//or any other code
MessageBox.Show("Done");
}
I have tried to remove update KB3132372 as suggested on this link, but it did not help.
Why does this code works fine on windows 8.1 or Windows Server 2012, but it does not work on two separate windows 10 machines?
I have the same issue. DocumentCompleted Event is never called when ReadyState == WebBrowserReadyState.Complete.
The issue I have is that the "Document.Body.KeyDown" event cannot be called unless the Body is created. It is created of course when the document is completed.
The hack I found is to create a while loop and execute a "Application.DoEvents()" until the "ReadyState == WebBrowserReadyState.Complete". Right after that you can be certain that the Document has been completed.

How to manage the onClose of windows phone 8.1 application

I would like to manage the behavior of my application when it closes (and not when it is suspended), but I couldn't find any method to override.
In this application, a user can log in with his profile: when he is in the main page of the application and presses back button, the app goes suspended and it's ok then that if it's resumed the user is still logged; what I want to do is that if the application is closed, the user won't be logged anymore, and if he opens the app again he has to log in again.
When the login is successful, I set local settings this way:
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["Logged"] = true;
So I would like to set to "false" the value of logged whenever the application is closed (not suspended), but like I said I couldn't find any kind of "on close" method to override.
The only way I've found to achieve what I want is to set
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
localSettings.Values["Logged"] = false;
in the "OnLaunched" method in App.xml.cs, but it's not working fine.
Define a handler vor the Application.Suspending event (https://msdn.microsoft.com/en-us/library/windows.ui.xaml.application.suspending).
The system suspends your app whenever the user switches to another app or to the desktop, and resumes your app whenever the user switches back to it. However, the system can also terminate your app while it is suspended in order to free up resources.
So there is no special event for closing the app.

Semantic Application Logging Block - Console logging in asp.net application

I am using Semantic Logging Application Block in our asp.net c# application. I am developing using Visual Studio 2013. I have created a listener which logs to a flat file and this works fine.
But I cannot get Console.LogToConsole to work. i.e., I don't see the log message in the Visual Studio Output window. I have checked the Immediate window and the log messages are not visible there either. Any suggestions are much appreciated.
Bit late to the party but you can create a custom event listener that writes to whatever you prefer (in this case Debug) like so:
internal class MyEventListener : EventListener
{
protected override void OnEventSourceCreated(EventSource eventSource)
{
base.OnEventSourceCreated(eventSource);
Debug.WriteLine("Listener attached to the source");
}
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
ICollection readOnlyCollectionObject = (ICollection)eventData.Payload;
object[] payload = new ArrayList(readOnlyCollectionObject).ToArray();
Debug.WriteLine(eventData.Message, payload);
}
}
And then, with our custom event listener built, we simply fire it up in the normal fashion:
var listener = new MyEventListener();
listener.EnableEvents(MyEventSource.Log, EventLevel.Informational);
MyEventSource.Log.MyEvent("Hello from the Immediate window!");
Credit to: http://www.shujaat.net/2013/08/slab-reactive-event-sourcing.html
I ran into the same thing as I first started with visual studio. Console.LogToConsole does what it says, logs to the console in a console app. Neither the Output nor Immediate windows are the console. The console looks like a DOS window. You wouldn't see this running an ASP.Net site. You would have to specifically create a console application. One note to mention, if you're debugging or running a console app within visual studio, sometimes the console window would be behind visual studio. Look for the icon that pops up in your windows task bar. Hope this helps!

Categories