UWP FolderPicker.PickSingleFolderAsync fails with COMException / E_FAIL - c#

In my UWP app I have the following code:
private async void testButton_Click(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FolderPicker();
StorageFolder folder = await picker.PickSingleFolderAsync();
}
but when I run this it fails on the second line with the message An exception of type 'System.Runtime.InteropServices.COMException' occurred in .... but was not handled in user code. The HRESULT from the exception is -2147467259 = 0x80004005 = E_FAIL.
I'm using file pickers already elsewhere in the app without problem. This is running on a Win10 desktop (launched from VS2015). Can anyone suggest why the error occurs and/or what to do to resolve it? Having a meaningless error message in what appears to be the simplest code possible I'm not sure how to proceed.

This is a bit of an oddity in WinRT. Although it is not mentioned in the documentation explicitly, it is necessary to add at least one item in the FileTypeFilter collection:
var folderPicker = new FolderPicker();
folderPicker.FileTypeFilter.Add("*");
await folderPicker.PickSingleFolderAsync();
You can use a specific extension like ".jpg", but it doesn't seem to have effect in a FolderPicker anyway. The only thing that matters is that at least one valid item is present.

Related

URI correct but incorrect at run-time?

My file, located at 'C:/Users/Username/Desktop/sample.pdf' is there. I can open it manually and it loads fine. Now if I put an invalid link, such as, file:///sample.pdf, which clearly can't be found, the Hololens app will open the Edge browser attempting to open the pdf. So, it's clear the code is functioning.
So why then is this uri incorrect when loading in the Hololens at run-time?
string uriToLaunch = "file:///C:/Users/Username/Desktop/sample.pdf";
// Create a Uri object from a URI string
var uri = new Uri(uriToLaunch);
Task task = new Task(
async () =>
{
// Launch the URI
var success = await Windows.System.Launcher.LaunchUriAsync(uri);
if (success)
{
// URI launched
}
else
{
// URI launch failed
}
});
task.Start();
task.Wait();
Here is the exception thrown.
Exception thrown: 'System.ArgumentException' in Assembly-CSharp.dll
WinRT information:
The provided URI scheme can't be launched.
Unhandled 'Platform.InvalidArgumentException' exception caught! - 'The parameter is incorrect.'
The parameter is incorrect.
The provided URI scheme can't be launched.', Sender: 'null'. Missing try/catch blocks.
The tricky thing with these exceptions in the Hololens is sometimes they don't seem to be related to whats not working. I've tried googling the error and nothing helpful appears.
EDIT: string uriToLaunch = #"file:///Data/myFiles/sample.pdf";
returns WinRT information: The provided URI scheme can't be launched.
The parameter is incorrect.
string uriToLaunch = #"/Data/myFiles/sample.pdf";
returns UriFormatException: Invalid URI: The format of the URI could not be determined.
NOTE I thought I could open the Edge browser from the app but I'm having trouble replicating this functionality. The only thing that responds, positively, shall we say, is
#"ms-appx:///Data/myFiles/sample.pdf";
This opens up a separate dialog box that will take my to the MS store to try and buy an app that will open ms-appx files.
EDIT 2:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
Task task = new Task(
async () =>
{
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
// Application now has read/write access to the picked file
Debug.Log("Picked photo: " + file.Name);
}
else
{
Debug.Log("Cancelled");
}
});
task.Start();
task.Wait();
I've tried implementing this simple FileOpenPicker, just to test and see if I could get one working, to no success.
It throws this:
Exception thrown: 'System.Exception' in mscorlib.ni.dll
Unhandled 'Platform.COMException' exception caught! - 'Invalid window handle.
EDIT 3: This is all I can find on the error.
COMException
If the ErrorCode property of the exception has the value 0x80070578 (ERROR_INVALID_WINDOW_HANDLE), this indicates that the method was not called on the UI thread.
EDIT 4: Now it's crashing and returning:
Exception thrown: 'System.Exception' in mscorlib.ni.dll
The program '[4084] hololensapplication.exe' has exited with code -1073741189 (0xc000027b).
As #AVK points out, UWP apps are sandboxed. This means files outside of the Hololens local environment aren't reachable. There are local known folders on the HoloLens, but the only way to get around this is to use third party apps such as OneDrive, Azure, etc.

async Pedometer.GetSystemHistoryAsync API for Universal apps crashes

I'm trying to throw together a simple app that uses pedometer data on a Windows 10 phone. I normally live down in kernel-land, and this is my first time using most of the c# async stuff, so I'm wondering if I'm missing a core concept here.
My first attempt at getting data out was to simply report the number of recorded steps over the last hour to a textbox in my XAML app. I just created a basic XAML app, dropped a text box in, and added this event handler:
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
var history = await Pedometer.GetSystemHistoryAsync(DateTimeOffset.Now.AddHours(-1), TimeSpan.FromHours(1));
int count = history.Sum(entry => entry.CumulativeSteps);
textSteps.Text = count.ToString();
}
A breakpoint on the first line triggers, but before it hits the next line I get an unhandled exception. Error code -2147467259, message "Error HRESULT E_FAIL has been returned from a call to a COM component."
The top frame of the stack is in my code, but it's just the boilerplate line from App.g.i.cs that triggers a break on an unhandled exception. Below that is mscorlib and the WinRT invoker.
I looked through the app capabilities list in the manifest, and didn't find anything that looked like it applied to the pedometer. I'm testing this on a Lumia 950.
UPDATE: I just tried calling the API to get the default pedometer sensor:
Pedometer p = await Pedometer.GetDefaultAsync();
It turns out that this triggers an access denied exception with the same worthless stack. I'm currently doing more research to see if there is something that needs to be specified in the manifest.
After further experimenting got me an access denied error, I looked into the manifest more. The manifest Microsoft example project for the pedometer declares a device property that I can't find a way to add through the designer view. Adding it to the code worked perfectly. It's saying I've taken 300,000 steps in the last hour, but I'm sure some simple debugging will find the answer there. (The property is called CumulativeSteps, so that's a good hint...)
<Capabilities>
<DeviceCapability Name="activity" />
</Capabilities>
var currentReadings = await Pedometer.GetSystemHistoryAsync(DateTime.Today);
var walklist = new List<PedometerReading>();
var runlist = new List<PedometerReading>();
foreach (var cuurentreading in currentReadings)
{
if (cuurentreading.StepKind == PedometerStepKind.Walking)
{
walklist.Add(cuurentreading);
}
if (cuurentreading.StepKind == PedometerStepKind.Running)
{
runlist.Add(cuurentreading);
}
}
var item = walklist.Last();
var item1 = walklist.First();
var item2 = runlist.Last();
var item3 = runlist.First();
Steps1.Value += (item.CumulativeSteps - item1.CumulativeSteps);
Steps1.Value += (item2.CumulativeSteps - item3.CumulativeSteps);

System.ExecutionEngineException on Windows 10 device

I am developing a Windows Phone 8.1 app. It works fine on WP 8 and WP 8.1 devices, but on the device with Windows 10 it throws
ExecutionEngineException was unhandled. An unhandled exception of type 'System.ExecutionEngineException' occurred in Unknown Module.
in various sections in both "Debug" and "Release" without any data about what went wrong. There are some places, where the exception is always thrown and some, where it's thrown from time to time. Example code below throws the exception - it is basically a method to switch between tabs, which are StackPanels when the button (Grid with Image) is tapped:
private void Grid_Tapped(object sender, TappedRoutedEventArgs e)
{
if(!isMapVisible)
{
hideSection();
map_wrapper.Visibility = Windows.UI.Xaml.Visibility.Visible;
map_button.Background = new SolidColorBrush(ColorHelper.FromArgb(0xFF, 40, 110, 73));
map_icon.Source = new BitmapImage(new Uri(FileHelper.getIconPath("tu_2.png")));
isMapVisible = true;
}
}
private void hideSection()
{
if(isMapVisible)
{
map_button.Background = new SolidColorBrush(ColorHelper.FromArgb(0xFF, 238, 238, 238));
map_icon.Source = new BitmapImage(new Uri(FileHelper.getIconPath("tu.png")));
isMapVisible = false;
map_wrapper.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
else if(isPhotoVisible)
{
photo_button.Background = new SolidColorBrush(ColorHelper.FromArgb(0xFF, 238, 238, 238));
photo_icon.Source = new BitmapImage(new Uri(FileHelper.getIconPath("photo_green.png")));
isPhotoVisible = false;
image_wrapper.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
else if(isListVisible)
{
list_button.Background = new SolidColorBrush(ColorHelper.FromArgb(0xFF, 238, 238, 238));
list_icon.Source = new BitmapImage(new Uri(FileHelper.getIconPath("!2.png")));
isListVisible = false;
news_wrapper.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
}
}
Finally I managed to fix the code. However the error wasn't in the code above. I used something called "Safe Navigation". The example is shown in the code below:
Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
rootFrame.Navigate(typeof(MainPage));
});
I also handled all asynchronous methods with await operator (I had left some of them before to run asynchronously). One of those improvements fixed the error.
I know this comes over two years beyond the original post, but maybe this will help someone looking for an answer to this question. I kept getting apparently random System.ExecutionEngineExceptions from a Window 10 UWP desktop app. After several days, I found the answer for my particular problem. I had used a MVVM platform, and the x:UID in one of my views had become corrupted.
IT SHOULD HAVE BEEN: <TextBlock x:Uid="Battery ...
IT WAS: <TextBlock x:Uid="=Battery"
The error was not flagged as a XAML problem, as many syntax errors similar to this are but once I corrected that error, by removing the unneeded equal sign, the exception went away.
Hope this helps someone else.
Clyde
Also want to add to the above. The XAML engine does not check for duplicate x:Uid and I also got this error when I had two x:Uid's with the same name. Made all x:Uid's throughout my project unique (unfortunately expands the resource file) but that resolved any further issues. Wished that the XAML designer checked for duplicate x:Uid's the was it does for x:Name's.
Again, hope it helps someone in the future.
Cheers,
Clyde
For those encountering ExecutionEngineException while using Xamarin, make sure you have the latest version of Microsoft.NETCore.UniversalWindowsPlatform.
The issue was fixed in UWP 6.2.12:
Fix to execution engine exception when loading InAppUI in Xamarin.
https://github.com/microsoft/dotnet/blob/main/releases/UWP/net-native2.2/README.md

Xamarin Android - Webclient

I'm trying to build an app for android (school project (technology)), however,
I'm keep getting an error and searching on the internet, gave no answer. So I'm hereby asking in here.
I got an MySQL 5.6 Server up and running, it works. PHP standalone and Xampp for file directory, and everything works fine in browser. The error occurs on the the arrow sign and exception error is about access (I think). I can upload the PHP files if needed.
The first one is a button, the second is an event fired when download is complete.
private void LoginButton_Click(object sender, EventArgs e)
{
TextView userName = FindViewById<TextView>(Resource.Id.editTextUsername);
TextView userPass = FindViewById<TextView>(Resource.Id.editTextPassword);
client = new WebClient();
url = new Uri(#"http://127.0.0.1/memento/accountcheck.php");
//url = new Uri(#"http://127.0.0.1/memento/phpinfo.php");
/*
NameValueCollection parameters = new NameValueCollection();
parameters.Add("Username", userName.Text);
parameters.Add("Password", userPass.Text);
*/
client.DownloadDataCompleted += Client_DownloadDataCompleted;
client.DownloadDataAsync(url);
}
private void Client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
Console.WriteLine(e.Result); // <------
}
EDIT:
Unhandled Exception: System.Reflection.TargetInvocationException: An exception occurred during the operation, making the result invalid. Check InnerException for exception details.
Exception Settings: C++ Exceptions, Common Language Runtime Exceptions, JavaScript Runtime Exceptions, Managed Debugging Assistants & Win32 Exceptions.
Each contain tons of check checkboxes except JavaScript. It contains one "0x80070005 Access is denied".

How do you check if a storagefolder is null c#

I'm surprised this has not come up before and im thinking im just not using the right search terms but been stuck on this for an hour now.
heres the issue, when some one presses the roll button on my app i want a folder picker to appear and allow the person to pick a folder, then the files are saved in that folder. I only want it to run once.
heres what i have
FolderPicker folder =new FolderPicker();
folder.FileTypeFilter.Add(".html");
folder.ViewMode = PickerViewMode.List;
folder.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
folder.SettingsIdentifier = "folder";
theFolder = await folder.PickSingleFolderAsync();
StorageFile file = await theFolder.CreateFileAsync(name + ".html", CreationCollisionOption.ReplaceExisting);
this works but ofcourse the picker appears every time i run the method (as its setup to do at the moment.
StorageFolder theFolder set up at the start of the programs run simply as
public StorageFolder theFolder;
i have tried changing
theFolder = await folder.PickSingleFolderAsync();
to
while (theFolder.Equals(null))
{
theFolder = await folder.PickSingleFolderAsync();
}
but that just causes a crash
"Object reference not set to an instance of an Object."
i also tried getting the display name of the folder and if it was blank then getting the folderpicker to show...same error
I can not even just have the folder picker show every time the person clicks run as a click of cancel will crash it (and it would be very annoying to the user)
any ideas ?
my app is a universal app in c# for windows phone and store, it is the windows store version im currently working on
If variable is null you can't call method on it.
while (theFolder == null)
{
theFolder = await folder.PickSingleFolderAsync();
}

Categories