Closing windows phone app programmatically - c#

I am using the following code to check for network access in the start of my application
public async void CheckNetwork()
{
if (!NetworkAvailabilty.Instance.IsNetworkAvailable)
{
MessageDialog Message = new MessageDialog("Network access not available.", "Network Error");
Message.Commands.Add(new UICommand("Close"));
await Message.ShowAsync();
Application.Current.Exit();
}
}
This works as expected in Windows 10 desktop. But when I am running the app in my Phone, it fails to close the app. What could be the reason for this and how to force close my app ?

As a design principle, you are not supposed to manually close an app. Please refer to this link (adressed to WP8 developers, but is still valid).
But, if you are working on a test app for yourself, you can throw an exception which is the only way possible to close the app.
throw new Exception();
Please don't do that if you aim to publish your app on the market :
An unhandled exception in your app consumes resources unnecessarily both on the user’s phone and on the Windows Phone servers.
The phone generates and uploads crash dumps for unhandled exceptions to help you find and fix bugs in your code. Crashing your app to close it wastes the user’s battery power and network bandwidth.

try Application.Current.Terminate() instead of Exit()

Try execute ApplicationView.GetForCurrentView().TryConsolidateAsync().

Related

How to use Geolocator.RequestAccessAsync in WPF desktop app

I've built a WPF app in C# which needs to know the user's location, and currently requires that it be entered manually. I'm using the Desktop Bridge to make it be able to run as a UWP app. When it's running as a UWP app, I want to take advantage of the Windows 10 location API if it is enabled. I'm using the following code to request for location access when the program starts:
public static async void RequestAccess()
{
var accessStatus = await Windows.Devices.Geolocation.Geolocator.RequestAccessAsync();
switch (accessStatus)
{
case Windows.Devices.Geolocation.GeolocationAccessStatus.Allowed:
UwpDesktop.hasLocationAccess = true;
break;
case Windows.Devices.Geolocation.GeolocationAccessStatus.Denied:
UwpDesktop.hasLocationAccess = false;
break;
case Windows.Devices.Geolocation.GeolocationAccessStatus.Unspecified:
MessageBox.Show("Failed to access Windows 10 location API", "Error");
UwpDesktop.hasLocationAccess = false;
break;
}
}
However I get the following error when I run my app if the location permission is not enabled for it:
System.Exception: 'Element not found. (Exception from HRESULT: 0x80070490)'
The cause of this error as far as I can tell is that the RequestAccessAsync function needs to be run in the main UWP UI thread. The reason it only happens when the location permission is not enabled is because Windows tries to launch a UWP dialog requesting that the user grant location access, but fails to do so in a Desktop Bridge app.
I'm aware of two solutions to this problem. One would be to launch the Location section of the Settings app and show a messagebox to users asking them to grant location access there, which could work but I would really prefer to use the official API. The other option is to create a new UWP code project and write this code there, and then run it from the WPF app.
Microsoft has some documentation that is supposed to explain how to do the second option, but their examples are complicated and I don't know how to apply them to what I'm trying to do. I don't want to create a XAML UI or a background service, all I need is a way to safely call RequestAccessAsync and return a value based on the outcome. I'm wondering if I really need to create a UWP project to make this behave the way I want, or what the simplest way would be to go about it.

extendedExecutionSession : Can we run UWP like Desktop app without Suspending?

I'm planing to start a UWP application that monitor a sensor data for 365 days and save all data to database(Sqlite).
I still worry about UWP capability. Please advice me Which should I use (UWP/WPF) ? I want to use better UI, than, I want to use UWP if possible...
UWP-Suspending is my worry.
With this post, Some people said a way to prevent a UWP application from suspending..
var extendedExecutionSession = new ExtendedExecutionSession();
extendedExecutionSession.Reason = ExtendedExecutionReason.Unspecified;
var extendedExecutionResult = await extendedExecutionSession.RequestExtensionAsync();
if (extendedExecutionResult != ExtendedExecutionResult.Allowed)
{
//extended execution session revoked
extendedExecutionSession.Dispose();
extendedExecutionSession = null;
}
Question
If I wrote this code in UWP app, Can I use a UWP application like Desktop WPF application ? I want to run my UWP application for 365 days without stopping
.. even if user do "minimized" on desktop... Please advice it...
Yes, you can do that with ExtendedExecution. One thing to note is when you run on battery (e.g. laptop, tablet) you will get suspended after some time - however you can prevent that as well by going into the Battery settings page and set your app as "Always Allowed".
Details are documented here: https://learn.microsoft.com/en-us/windows/uwp/launch-resume/run-minimized-with-extended-execution

How to troubleshoot remote UWP AppService problems?

I'm playing around with remote UWP AppServices in C# and I run into a very early roadblock: Getting a RemoteSystem instance.
I followed the tutorial on https://msdn.microsoft.com/en-us/windows/uwp/launch-resume/communicate-with-a-remote-app-service with my own code and I tried out the RemoteSystems sample as part of https://github.com/Microsoft/Windows-universal-samples
Unfortunately, the result is always the same.
First I request access to remote systems:
RemoteSystemAccessStatus status = await RemoteSystem.RequestAccessAsync();
This is successful: status has the value RemoteSystemAccessStatus.Allowed.
Next, I create a HostName instance:
var deviceHost = new HostName("computer2");
Then I want to get a RemoteSystem instance:
RemoteSystem remoteSystem = await RemoteSystem.FindByHostNameAsync(deviceHost);
This throws an exception:
Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
What I tried
Searching the web doesn't bring up much at this time (remote UWP AppServices are too new)
The event log doesn't have anything interesting in it
The Windows firewall seems to be configured correctly (this seems to be done automatically by Visual Studio)
What I'm looking for
One of my computer was upgraded from Windows 7 to Windows 10, the other from Windows 8.1 to Windows 10. So there is a chance my computers are "misconfigured" in some way (I remember the unnecessary task scheduler entries for Windows Media Center...)
My question: What are recommended practices to troubleshoot these kinds of problems? Are there tools that can help me? Right now I'm now even sure where to start looking...

Check if Windows.System.Launcher.LaunchUriAsync was handled

I try to solve problem with the Windows Phone Launcher.
I have application and I would like to call another application using the uri and pass it some data. And I would like to know if the second application started. If the application was not started I would like to do some fallback.
Example:
bool result = await Windows.System.Launcher.LaunchUriAsync(new Uri("secondApp://data/123", UriKind.RelativeOrAbsolute));
if (!result)
{
// Opps. The second application is not installed.
ShowToast("Oops. The applications is not installed.");
UseInternalTinyFunctionalityInstead();
}
But the result is always true. Even though the second application is not installed. And additionally the windows message box is displayed "Search for app in the Store? You need to install an app for this task. Would you like to search for one in the Store? yes, no".
Is it possible to check if the second application was started/ is installed?
Is it possible NOT to display this dialog?
Thank you.
Myth Rush

Cannot stop the service using ServiceController in .NET 3.5

I'm working in .NET 3.5 and I have the problem with stopping some service using ServiceController. I searched whole internet and I found no solution to my problem ;)
Here's how I do that:
using (ServiceController service = new ServiceController("Service"))
{
try
{
TimeSpan timeout = TimeSpan.FromSeconds(timeoutSeconds);
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
I'm waiting until my service stops. Then I want to replace it's libraries (update it). And the exception is thrown:
UnauthorizedAccessException
Exception Details: System.UnauthorizedAccessException: Access to the path 'blablabla' is denied.
I'm sure that I have access to this path, because I run my application as an Administrator.
What is interesting when this piece of code executes, this Service disappear from the List of current services (in Task Manager). So it actually stops it, but some thread has to still use it, so I can not move any Service's files. Even when I try to move files by myself (I go to the Service directory and try to move its files using mouse) I can not do it. But when I stop the Service manually (Task Manager and 'End Task') I can do whatever I want with its files. So what's the difference between stopping it from C# code (using ServiceController) and stopping it using Task Manager?
I don't know if it's important but I run this application (and this Service) on Windows Server 2008 in Virtual Box. (I needed to run it on some other machine then my computer).
Any ideas how can I solve this problem? ;)
Thanks for any help.
Best wishes,
Pete.
Ok, I solved my problem.
First I used an Administrator Command-Prompt Command of Net Stop to stop the Service and it worked, but I started to wonder why. The answer is it took a lot of time!
ServiceController actually stopped it, but some processes was still using it.
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
Also workerd fine, because it imidaitely changed the status of the service (it's just one change in Windows Services list), but closing politely all threads using certain Service takes some time :)
So all You need to do is just wait, and then check again if it's still running. If it is, then kill it with Process class.

Categories